1

I have a logfile that is generating hundreds of lines per second – say, 12 specific lines, 16× per sec.

I want to run either a command-line or a shell script that can display this logfile neatly in real-time. But if I run tail -f logfile.txt, the text rapidly scrolls off the terminal window and can't be read by human eyes. I haven't yet mastered the command line so this is all I can think of doing right now.

I want the terminal window to just print 12 lines at a time and automatically refresh, something like:

// while ( Ctrl+C hasn't been hit )
// {
//   clear terminal window
//   print last 12 lines of logfile.txt
//   wait until logfile is 12 lines longer
// }

Any ideas?

EDIT: it turns out I can do tail -f logfile.txt and just set the terminal window height to 12. This gets me pretty close to what I want, but it seems like a "naive" approach. Hoping somebody has a more elegant solution.

2
  • 1
    The description conflicts with itself. Your while loop would be run 16 times/s. How would you read 12 lines in a fraction of second? I recommend you to use the scroll lock key.
    – Quasímodo
    Commented Jul 21, 2020 at 17:24
  • I have recently answered unix.stackexchange.com/q/598508, is it what you want?
    – Quasímodo
    Commented Jul 21, 2020 at 18:11

4 Answers 4

1

You can view the last N lines at a M second interval using watch. Assuming N=20 and M=3,

watch -n3 tail -n20 logfile.txt

Obviously you'll lose great chunks of output as the update interval exceeds the write interval, but as far as I understand it this is what you want.

2
  • "The command will not allow quicker than 0.1 second interval" -- but otherwise, very much what I was looking for
    – Lagrangian
    Commented Jul 23, 2020 at 19:14
  • I thought you wanted to be able to read the output, in which case wouldn't 0.1s be too fast? Commented Jul 23, 2020 at 19:55
1

Bash >= 4 has a special built-in function mapfile:

tail -f logfile.txt | while mapfile -t -n 12 lines && ((${#lines[@]})); do
    clear
    printf '%s\n' "${lines[@]}"
    sleep 0.1 # Might be necessary or you won't see anything at all except the last batch of lines
done

Adopted from: Read n lines at a time using Bash.

1

I like to use less for looking at logs. Some useful less commands:

  • G to jump down to the last line
  • R to refresh the file (followed after by G)
  • F to tail the file in real time (aka tail -f): hit Ctrl+C to stop tailing.
1
  • Ha, I read that too fast--I thought you wrote: "some less useful commands". Pays to read slower! Commented Oct 20, 2022 at 5:16
0
tail -f logfile.txt | less

And you can use the interface glenn jackman highlighted to move about:

  • F to follow
  • Ctrl-C to stop following
  • q to quit
  • / to search for regular expressions

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .