Archive

Posts Tagged ‘sysadmin’

Finding what’s after a specific string in a text-file

November 7th, 2009 Fighter Hayabusa No comments

Have you ever wanted to find a specific string in a log-file and then output what comes after that line in the file? I do this every single day at work and can’t be the only one. Somewhere in a huge log-file, XML-file or other type of text-file there’s a line that equals the beginning of some specific type of information that I’m in need of so I need to find that line of text and output a bunch of the lines following it.

I might for example have a backup cron-job that when it starts outputs “Backup started” to /var/log/messages and then follows that with output concerning how the backup went. Sure, theoretically I could open the file in vim and simply search for the line in question but sometimes text-files are frikkin’ huge and opening them up in a text-editor is just not a viable option. For example, I handle XML-files that are several gigabytes in size daily and loading one of those into an editor will mean nothing but pain and suffering I assure you ;-)

So to facilitate this procedure I slapped together this script, which I’m giving the easy-to-remember name fsagsl.sh:

#!/bin/bash
# fsagsl.sh Find String And Grab Some Lines
# 2009 (c) IDontGiveASmegWhatYouDoWithIt License
# by FighterHayabusa <fighterhayabusa@barbedwirebytecodebaconburger.com>
# Finds a string in a text-file and then outputs
# a chosen number of lines from that position onwards.

function is_int()
{
[ "$1" -eq "$1" ] > /dev/null 2>&1
return $?
}

PRG=fsagsl.sh

if [ -f $3 ] && is_int $2; then
LINESTART=`grep -n $1 $3 | sed -e 's/\([0-9]*\):.*/\1/g'`
for L in $LINESTART; do
let LINESTOP=$L+$2
sed -n "${L},${LINESTOP}p" $3
done
exit 0
else
echo "ERROR: Invalid parameters."
echo "Usage: ./$PRG string_to_find number_of_lines filename"
echo "Example: ./$PRG \"Backup started\" 5 /var/log/messages"
exit 1
fi

As you may notice the script also has some simple error-handling and  handles if there are multiple instances of the string that is being looked for.

So there you go. I hope somebody finds it useful :-)