Reputation: 183
I have file which contains some lines and some numbers. I want to delete all the lines after particular string, let us say the string is 'angles'. I want to delete all the lines after angles, I can do this using sed command as follows:
sed -n '/angles/q;p' input file
My question is, I want to delete all the lines after angles but want to retain the last four lines? How can I do this in sed?
Upvotes: 1
Views: 455
Reputation: 247012
I'm going to assume the string you're looking for may occur more than once, and you only want up to the first one. If that's true, reversing the file isn't the best strategy.
{ sed '/angles/q' file; tail -4 file; } > result
Upvotes: 0
Reputation: 204015
awk -v size=$(wc -l < file) '
/angles/ { skip=1 }
NR >= (size-4) { skip=0 }
!skip
' file
Upvotes: 0
Reputation: 58483
This might work for you (GNU sed):
sed '1,/angles/b;:a;$!{N;s/\n/&/4;Ta;D}' file
Print out all the lines from the first till encountering the string angles
. Then make a moving window
of four lines and print them at end of file.
Upvotes: 1
Reputation: 67291
In awk :
awk '{
if(p!=1)print;
else{a[NR]=$0}
if($0~/angles/)p=1
}
END{
for(i=NR-3;i<=NR;i++)print a[i]
}' your_file
Tested below:
> cat temp
wbj
ergthet
gheheh
wergergkn angles gerg
er
ergnmer
rgnerk
1
2
3
4
> awk '{if(p!=1)print;else{a[NR]=$0};if($0~/angles/)p=1}END{for(i=NR-3;i<=NR;i++)print a[i]}' temp
wbj
ergthet
gheheh
wergergkn angles gerg
1
2
3
4
>
Upvotes: 0
Reputation: 123608
The following should work for you:
tac inputfile | sed '5,/angles/d' | tac
Explanation: Reverse the file, keep first 4 lines and delete everything until the desired pattern is encounterd. Reverse the result.
Upvotes: 1