简体   繁体   中英

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?

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
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.

Well, here's a simple grep :

grep -B100000000 string2 yourfile

Just make that number bigger than the number of lines in your file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM