linux Solutions

Tailing the output of multiple files in Linux

This is a quick post to show a trick to tail multiple files, while showing the filename in the beginning of the line
What I needed was a way to grep multiple logs for an exception. But doing “tail -f *.log | grep exception” only let me see the exception, but I didn’t know which log file to look in
I have found this guide, and altered the script and added

  1. Printing the file name in the beginning of each line
  2. Padding spaces after the file name (you can alter the minimal length in the ALIGN variable

Anyway – here’s the script. Hope you find it useful

# When this exits, exit all back ground process also.
trap 'kill $(jobs -p)' EXIT
# iterate through the each given file names,
for file in "$@"
        LENGTH=`echo ${file} | wc -c`
        PADDING=`expr ${ALIGN} - ${LENGTH}`
        PAD=`perl -e "print ' ' x $PADDING;"`
        # show tails of each in background.
        tail -f $file | sed "s/^/${file}${PAD}:/g"  &
# wait .. until CTRL+C