-1

How can I remove any line beginning with --- occurring in any line number after a line containing # Match (the first occurrence in any line number)?


EDIT:

The relationship between #Match with the lines starting with --- is that the later can exist before or after #Match but it should be removed only if it exists after #Match. –

Sample Input

hello

this is sample
--- sdafasdf
adsafasf
asfas
fasf

#Match
this is sample
adsafasf
asfas    dafasf
------ lots of fun
---- test

adsfasf****

Expected Output

hello

this is sample
--- sdafasdf
adsafasf
asfas
fasf

#Match
this is sample
adsafasf
asfas    dafasf

adsfasf****
2

Based on your question, i just created this text.txt. If your file contents are different, then let us know.

bash-4.1$ cat test.txt
#Match
---- test
hello
#Match
this is sample
adsafasf
asfas
fasf
#Match
------ funny
------ lots of fun
#Match
dafasf
adsfasf

bash-4.1$ awk '/#Match/ {flag=1} flag && /^---/ {flag=0;next} 1' test.txt
#Match
hello
#Match
this is sample
adsafasf
asfas
fasf
#Match
------ lots of fun
#Match
dafasf
adsfasf
  • P.s, just informing that question is revised now, and you need update your answer as well. – αғsнιη Sep 14 '18 at 12:31
1

Using sed:

sed -e '/#Match/ {n; /^---/d; }' infile

The n command is reading the next line of input into the pattern space and /^---/d deletes that line if it starts with --- only when previous line matched with #Match.

Answer to the revised question:

sed -e '/#Match/,$ { /^---/d; }' infile
  • Hi did you try it on the sample input? Surprisingly, I didn't succeed with your answer. – Nikhil Sep 14 '18 at 11:49
  • 1
    of course I tested. double check your pattern #Match if that exist in your file. If doesn't work, then please edit your question and add how do you tried and what you are getting (avoid saying doesn't work word only instead of details ) – αғsнιη Sep 14 '18 at 11:53
  • Hi could you please explain what is the use of $ here? – Nikhil Sep 14 '18 at 12:19
  • in sed if it's outside substitution command, means end of file, in substitution if come means end of line – αғsнιη Sep 14 '18 at 12:30
  • For a minor modification to the question should I ask it separately. Remove a whole line beginning with a pattern (and the next line) occurring anywhere before another pattern – Nikhil Sep 14 '18 at 13:09
0

How about

awk '/#Match/,EOF {if (/^---/) next} 1' file

Starting with a line matching #Match until the variable EOF will become true (which will never happen, thus = end of input stream), skip the actual line if it matches three (or more) dashes at the beginning.

  • We prefer answers to include an explanation. Compare to αғsнιη’s answer. – Scott Sep 14 '18 at 17:14

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.