0

I would want to only remove the lines between PATTERN1(aaa) and PATTERN2(ccc), excluding the others lines where the patterns matches.

I trying to delete the empty line between PATTERN1(aaa) and PATTERN2(ccc), line 8 in my example...This line will be no all times in same location, that is the reason, why I try to remove it using the 2 patterns.

Essentially it boils down to: "If a blank line is found between aaa and ccc then remove it...

input file

aaa 409 bbb 201 122 0.98 aaa 1.47 aaa 0.00 aaa 0.00 ccc 0.00 121 0.01 135 1.99 

output file

aaa 409 bbb 201 122 0.98 aaa 1.47 aaa 0.00 aaa 0.00 ccc 0.00 121 0.01 135 1.99 

attempts

sed '/aaa/,/ccc/{//p;d;}' file sed '/aaa/,/ccc/{//!d}' file awk '/aaa/{g=1;next}/ccc/{g=0;next}g' file 

Thank you in advance.

18
  • 1
    Try to says what you want to do in another way, so someone as stupid as /me can understand what you want to do .... 😁 Commented Feb 28, 2020 at 16:47
  • 1
    You already know sed isnt the right tool for this and you got answers to dozens of similar questions using awk so why even post sed attempts. Commented Feb 28, 2020 at 16:48
  • 1
    It's unclear why you do not want to remove the 3rd line. Is is also between aaa and ccc, and is also empty ? Commented Feb 28, 2020 at 16:54
  • 1
    But line 1 is using patter aaa and line 9 is using pattern ccc, and line 3 is an empty line...... Commented Feb 28, 2020 at 16:58
  • 3
    This is a tricky one. Essentially it boils down to: "If a blank line is found between aaa and ccc then remove it. Do not remove blank lines between patterns aaa and aaa" Commented Feb 28, 2020 at 17:07

1 Answer 1

2
$ cat tst.awk /aaa/ { printf "%s", block; block=""; inBlock=1 } !inBlock { print } inBlock { block = block $0 ORS if ( /ccc/ ) { gsub(/\n+/,"\n",block) printf "%s", block block = "" inBlock = 0 } } END { printf "%s", block } 

.

$ awk -f tst.awk file aaa 409 bbb 201 122 0.98 aaa 1.47 aaa 0.00 aaa 0.00 ccc 0.00 121 0.01 135 1.99 

The above removes all blank lines in the block of lines between ccc and the closest aaa before it. To isolate that block it starts the block when it sees an aaa and then restarts it (after printing what was stored as-is) if/when the next aaa is encountered before a ccc is encountered.

Sign up to request clarification or add additional context in comments.

1 Comment

Ed Morton, Thank you, maestro, code works perfectly. This is exactly what i was looking for. Thank you again.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.