Search code examples
bashsolaris

How can I automatically disregard the last three lines of a file?


I am using the following command:

 head -36 file.txt > file1.txt

where the file is 39 lines , but the thing is i'm checking that the file is 39 lines and so place the number 36 in the comment. So is there a way that the command calculates the number of lines and deduct the last 3 lines ?


Solution

  • And here is awk only solution (no process substitution, piping, etc.)

    awk 'NR==FNR{k++;next}FNR<=k-3' file.txt file.txt
    

    Explanation:

    • We add the file.txt two times, so that awk reads it twice. The first time it counts the total number of lines in the file, and the second time it prints all the lines, except the last three
    • NR==FNR{k++;next}: The NR variable is the record number (including both filee), and the FNR is the record number in the current file. They are equal only for the records in the first file. So, for the first file we count the lines in it, with k++, and then we skip the remaining commands with next.
    • FNR<=k-3 If the FNR variable is smaller that the total lines in the file (which we counted in the previous bullet) - 3, then expression evaluates to true, and the line is printed. Otherwise, the expression evaluates to false (for the last three lines), and the line is not printed. This only happens for the second file, because of the next command in the previous block.