Reputation: 21
So let's say I have a file that contains the following text:
string1
string1
string2
string1
string2
string1
string1
And I wanted to get rid of all text after the last occurrence of "string2". For example the output would look like this:
string1
string1
string2
string1
string2
What's an easy way to do this in bash?
Upvotes: 0
Views: 940
Reputation: 6198
Well, here's a simple grep
:
grep -B100000000 string2 yourfile
Just make that number bigger than the number of lines in your file.
Upvotes: 0
Reputation: 92904
grep approach:
grep -zo '.*string2' yourfile && echo
The output:
string1
string1
string2
string1
string2
-z
- treat input and output data as sequences of lines, each terminated by a zero byte (the ASCII NUL character) instead of a newline
To write the result into a file do the following action:
(grep -zo '.*string2' yourfile && echo "") > output.txt
Upvotes: 1
Reputation: 17058
tac file | awk '!f && /string2/ { f=1 }; f' | tac
tac
prints the file upside down. awk
sets a flag on first occurence of the pattern string2
(which is the last occurence in the original version) and prints a line only if the flag is set.
Upvotes: 1