0

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?

3 Answers 3

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

1
  • Thanks, you made my day! Commented May 28, 2017 at 18:41
1

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
4
  • Why doesn't it work for me? I only get two lines with string2.
    – steffen
    Commented May 28, 2017 at 18:36
  • @steffen, what's your OS and grep version? Commented May 28, 2017 at 18:41
  • grep (GNU grep) 2.20, OS is CentOS release 6.9 (Final)
    – steffen
    Commented May 28, 2017 at 18:46
  • Yes, I know, your answer makes perfectly sense to me (it will just load all the file content to RAM, but that's fine for most cases). I don't know why it doesn't work on my test machine. It like -z has no effect, but actually it does when run wihtout -o - then I get the whole file contents, not only the two lines.
    – steffen
    Commented May 29, 2017 at 14:11
0

Well, here's a simple grep :

grep -B100000000 string2 yourfile

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.