Categories
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

#!/bin/bash
# When this exits, exit all back ground process also.
trap 'kill $(jobs -p)' EXIT
ALIGN=31
# iterate through the each given file names,
for file in "$@"
do
        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"  &
done
# wait .. until CTRL+C
wait

2 replies on “Tailing the output of multiple files in Linux”

Nice. I was not familiar with this tool.
Can you let me know how I can use it to do the same as the script
basically: tail -f * | grep Exception # Only I need it to display the file name in the beginning
for a live exception search in log files

Leave a Reply

Your email address will not be published. Required fields are marked *