using awk, this will print all the lines except last two lines.
awk '{a[j++]=$0}END{for(i=0;i<j-2;i++){print a[i]}}' filename
题
Here's the file:
line1
line2
⋮
line10
Total
Update time
I want to have the first part of file except for the last 2 lines.
The output should look like this:
line1
line2
⋮
line10
How can i achieve this using BSD head? or other oneliner?
Thanks!
解决方案
using awk, this will print all the lines except last two lines.
awk '{a[j++]=$0}END{for(i=0;i<j-2;i++){print a[i]}}' filename
其他提示
Another awk option:
cat <<file>> | awk -v len=$(wc -l <<file>> | awk '{print $1}') 'NR < len - 2 { print $0 }'
reverse the file, delete the first 2 lines, then reverse back:
tac file | sed 1,2d | tac
The concept of this doesn't use much buffers and is useful even for extremely large files or endless streams in pipes. It should be better than any other solution provided so far. You also don't have to wait to get to the end before it starts printing the lines.
awk 'BEGIN{X = 2; getline; a[NR % X] = $0; getline; a[NR % X] = $0}{print a[NR % X]; a[NR % X] = $0}'
NR could also be replaced with another counter that resets itself to 0
if limit of NR is concerned. Also it would depend on the implementation of awk how it cleans itself up and reuse memory on every N
lines of input
but the concept is there already.
awk 'BEGIN{X = 2; for(i = 0; i < X; ++i)getline a[i]}{i %= X; print a[i]; a[i++] = $0}'
Something like
head file.txt -n -2
should work, provided your head
version allows the -2 argument. My version of GNU's head works
$ head --version head (GNU coreutils) 5.97 Copyright (C) 2006 Free Software Foundation, Inc. This is free software. You may redistribute copies of it under the terms of the GNU General Public License . There is NO WARRANTY, to the extent permitted by law. Written by David MacKenzie and Jim Meyering.
This might work for you:
[root@gc-rhel6-x64 playground]# cat file
line1
line2
line3
line4
line5
line6
line7
line8
line9
line10
[root@gc-rhel6-x64 playground]# head -`expr \`wc -l < file\` - 2` file
line1
line2
line3
line4
line5
line6
line7
line8
This will get the file except last 2 lines
cat file.txt | head -$(expr $(wc -l file.txt | cut -c-8) - 2)
change the bold part for modification.