简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM