1

Looking to use any command to produce the following outcome. Edited for greater clarity. I'm trying to remove any ^abc that is not a line before ^xyz.

stdout:

abc def
abc ghi
abc jkl
xyz mno
xyz pqr
abc def
abc ghi
abc jkl
xyz mno
xyz pqr

desired result:

abc jkl
xyz mno
xyz pqr
abc jkl
xyz mno
xyz pqr
3
  • Perhaps edit your code to show exactly where uniq would fail here? It would likely be relevant to the sed answer. (Is awk etc. allowed?)
    – Sparhawk
    Jun 25 '18 at 23:40
  • before what match? before a repeated line? before a line that repeats only in the first column?
    – Jeff Schaller
    Jun 26 '18 at 0:18
  • perhaps your example should be a bit more complete (showing the variation in what followed etc)
    – Jeff Schaller
    Jun 26 '18 at 0:19
1

You could maintain a two-line buffer (using a N D loop) and print the first line before deleting it only if there's a xyz in the buffer:

$ cat stdout | sed ':a; $!N; /xyz/P; D; ba'
abc jkl
xyz mno
xyz pqr
abc jkl
xyz mno
xyz pqr
1
  • Short and sweet; works like a charm; thank you! Now I need to study and assimilate that syntax! :)
    – Jer
    Jun 26 '18 at 1:36
0

Here is an awk one-liner.

awk '/^abc/ {prev = $0; prevabc = "true"}; /^xyz/ {if (prevabc == "true") {print prev; prevabc = "false" } ; print}' file.txt

Explanation

  • /^abc/ {prev = $0; prevabc = "true"};: If the line starts with abc, don't print it, but instead store the value of the line in the variable prev, and indicated that this line started with abc by storing true in variable prevabc.
  • /^xyz/ {if (prevabc == "true") {print prev; prevabc = "false" } ; print}: If the line starts with xyz, the do the following.
    • if (prevabc == "true") {print prev; prevabc = "false" }: If the previous line started with abc (because prevabc == "true"), then print the previous line prev and reset prevabc to false.
    • print: Since this line started with xyz, then print this line too.

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.