Reputation: 4152
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!
Upvotes: 0
Views: 217
Reputation: 75498
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}'
Upvotes: 2
Reputation: 246847
reverse the file, delete the first 2 lines, then reverse back:
tac file | sed 1,2d | tac
Upvotes: 2
Reputation: 8107
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
Upvotes: 1
Reputation: 2857
Another awk option:
cat <<file>> | awk -v len=$(wc -l <<file>> | awk '{print $1}') 'NR < len - 2 { print $0 }'
Upvotes: 2
Reputation: 1420
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
Upvotes: 2
Reputation: 4152
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.
Upvotes: 0
Reputation: 30210
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.
Upvotes: 1