1

I have below text:

add gmt version date
comment - text1
text1 continue
comment - text2
text2 continue
comment - text 3
text3 continue

I want all text from first occurrence of "comment" to end of file. I was using sed 's/^.*Comment - //g' I am getting only below text:

 text 3
 text3 continue

i.e. from last occurrence of "comment" to end of file. but I need all text from first occurrence of "comment" to end of text i.e.

    text1
    text1 continue
    comment - text2
    text2 continue
    comment - text 3
    text3 continue

closed as unclear what you're asking by Kusalananda, Mongrel, mdpc, GAD3R, roaima Feb 9 '17 at 17:05

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • I have updated post. I want all text after "comment - " and rest of lines ( 5 lines in above example) – user746184 Feb 9 '17 at 12:41
  • And with 's/^.*Comment - / /g' I am getting only 2 lines. – user746184 Feb 9 '17 at 12:43
  • 1
    You do realize that 4 lines in your input don't match that regex so it's impossible to get only 2 lines after running that command ? – don_crissti Feb 9 '17 at 12:44
0

Done with a pipe, but it's not very nice

$ sed -n '/comment/,$ p' file | sed -r '0,/comment/ s/comment - (.*)/\1/'
text1
text1 continue
comment - text2
text2 continue
comment - text 3
text3 continue
Explanation
  • sed -n '/comment/,$ p' file print lines from comment to the end
  • sed -r '0,/comment/ s/comment - (.*)/\1/' find the first line with comment and edit it to remove comment -
  • 1
    Note that -r and the 0 address are GNU specific. – Stéphane Chazelas Feb 9 '17 at 13:40
1

The easiest way to do this with sed is via command grouping:

{ sed '/PATTERN/!d;s///;q'; cat; } <infile

it deletes all lines that don't match, on 1st match it substitutes per your request and quits (autoprinting) then cat takes over and prints the remaining lines, if any.
Not to say you can't do it with sed alone:

sed '/PATTERN/,$!d         # delete all lines not in this range
//{                        # if the line matches
x;//!{                     # exchange and IF what was in hold space doesn't match
g;s///;b                   # get hold space content, replace, go to end of script
}
x                          # ELSE exchange back (do nothing)
}' <infile

I used PATTERN so as to keep it simple (replace it with ^.*comment - or whatever the pattern is).

  • 1
    See also sed '0,/PATTERN/{s///p;d}' with GNU sed. – Stéphane Chazelas Feb 9 '17 at 13:39

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