2

I have sample:

This is a test
localhost% This is a test

The first This is a test will re-appear in an txt file of next line that will has some chars localhost% before it. I'd like to remove the first This is a test if the next line contain something like <arbitrary characters>% This is a test

So I'd like to check two lines and if the previous line This is a test matched in next line localhost% This is a test (note about %), then delete the previous one.

How could I achieve this?

  • A little bit confused of myself, other tools would also works for me too. – Tuyen Pham Sep 20 '18 at 14:07
3

Maybe:

sed '$!N;/^\(.*\)\n.*% \1$/!P;D'

That is have sed work on a rolling 2-line pattern space by using N with D and remove the first line (skip it by not (!) Printing it) if it's found (\(...\) captured in \1) at the end ($) of the second line after "% ".

That should also work for things like:

This is a test
foo% This is a test
bar% foo% This is a test

(removes the first 2 lines).

  • Yeah, can you do sed?, and This is a test is content of line that need to be deleted after check with next line that contains that content. – Tuyen Pham Sep 20 '18 at 13:59
1

You can use below command

sed -i "/This is a test/s/^This is a test$//g" test && sed -i '/^$/d' test

Input file

cat test

This is a test
localhost% This is a test

After execution of above command

output file

cat test

localhost% This is a test
  • I think I should make more clear, This is a test is just one of the case, I'll update the #1. – Tuyen Pham Sep 20 '18 at 10:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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