简体   繁体   中英

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 ?

awk -v nr=$(wc -l <file) 'NR<(nr-2)' file
nl=`wc -l file.txt | awk 's=$1-3{print s}'`; head -n $nl file.txt

wc -l calculates the total number of lines. Using awk, you can print the total number of lines -3 . Then use head to read only that many lines...

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.

Hey you want to tell it how many lines to exclude, not how many you will end up with.

Also add the -n to check for an empty file.

head -n -3 file.txt


If not try with a temp file

 head -n -3 file.txt > temp.txt ; mv temp.txt file.txt 

This should work

head -n -3 file.txt

From man head

 -n, --lines=[-]K
          print the first K lines instead of the first 10; with the leading '-', print all but the last K lines of each file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM