ParadigmTheGreat
ParadigmTheGreat

Reputation: 21

Remove all text after the last instance of a string in Unix

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

Answers (3)

Jack
Jack

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

RomanPerekhrest
RomanPerekhrest

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

steffen
steffen

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

Related Questions