Harsha K L
Harsha K L

Reputation: 677

sed : Need to remove all lines except first or last line that matches a string

I have a text file with the following content

aa : 01
bb : 01
cc : 01
aa : 02
dd : 01
bb : 02
ee : 01
aa : 03
ff : 01
bb : 03

I need to keep first occurrence of line that has string "aa" in it and last occurrence of line that has string "bb" in it.

Please help. Output should be

aa : 01
cc : 01
dd : 01
ee : 01
ff : 01
bb : 03

Upvotes: 1

Views: 1524

Answers (1)

anubhava
anubhava

Reputation: 785611

You can use this awk:

awk '!c && /^aa/{c=1;print;next} /^bb/{l=$0;next} !/^aa/ {print} END{print l}' file
aa : 01
cc : 01
dd : 01
ee : 01
ff : 01
bb : 03

Upvotes: 3

Related Questions