Text Processing – Command to Display First and Last Lines of a File

catheadlogstailtext processing

I have a file with many rows, and each row has a timestamp at the starting, like

[Thread-3] (21/09/12 06:17:38:672) logged message from code.....

So, I frequently check 2 things from this log file.

  1. First few rows, that has the global conditions and start time is also given.
  2. Last few rows, that has the exit status with some other info.

Is there any quick handy single command that could let me display just the first and last few lines of a file?

Best Answer

You can use sed or awk to make it with one command. However you'll loose at speed, cause sed and awk will need to run through the whole file anyway. From a speed point of view it's much better to make a function or every time to combination of tail + head. This does have the downside of not working if the input is a pipe, however you can use proccess substitution, in case your shell supports it (look at example below).

first_last () {
    head -n 10 -- "$1"
    tail -n 10 -- "$1"
}

and just launch it as

first_last "/path/to/file_to_process"

to proceed with process substitution (bash, zsh, ksh like shells only):

first_last <( command )

ps. you can even add a grep to check if your "global conditions" exist.

Related Question