简体   繁体   English

sed:需要删除除了匹配字符串的第一行或最后一行之外的所有行

[英]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. 我需要首先出现其中包含字符串“aa”的行,并且最后一次出现具有字符串“bb”的行。

Please help. 请帮忙。 Output should be 输出应该是

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

You can use this awk: 你可以使用这个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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用sed删除除特定字符的前3个和最后一个之外的所有内容 - How to remove all except the first 3 and last of a specific character with sed “ sed”命令删除与第一个单词完全匹配的行 - “sed” command to remove a line that matches an exact string on first word sed - 删除匹配模式以外的所有行 - sed - Remove all of a line except matching pattern 如果它匹配第一个和最后一个搜索之间的任何字符串,除了空格,在记事本++中进行通配符搜索以获取特定行 - wildcard search in notepad++ to get particular line if it matches any string between first and last search except whitespaces 使用sed / awk,我需要从第一次出现的pattern1到(但不包括)最后一次出现的pattern2中删除文件中的所有行 - Using sed/awk, I need to remove all lines in a file from the first occurrence of pattern1 up-to (but not including) the last occurrence of pattern2 除第一个和最后一个以外的所有逗号都转义 - Escape all commas in line except first and last 使用sed,对于每个字符串,除了第一个字符串,均删除两行 - Using sed, for every occurrence of a string, except the first, delete two lines 如何在sed行中匹配除第一个匹配项以外的所有匹配项? - How do I match all but the first matches in a line with sed? 删除字符串中除第一次出现之外的所有出现 - Remove all occurrences in a string except the first occurrence 删除除最后一行以外的所有换行符 - Remove all line breaks except from the last line
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM