![](/img/trans.png)
[英]How to delete 5 lines before and 6 lines after pattern match using Sed?
[英]Using sed to remove all lines that don't match a pattern
sed非常新(意味着一天)。 我已经找到了一种方法,可以使用查找/替换单个命令来删除不需要更新文件的行
我有一个对象列表,如下所示:
config firewall address <--keep line
edit "item1"
next
edit "item2"
next
edit "item3"
next
edit "item4" <--keep line
unset associated-interface <--keep line and use as anchor for one line above and below
next <--keep line
edit "item5" <--keep line
unset associated-interface <--keep line and use as anchor for one line above and below
next <--keep line
edit "item6"
next
end <--keep line
我试图拥有它,所以当一切都说完之后,我试图保留三行(item4&item5)并删除所有其他行。 另外,如果可能,请保留第一行和最后一行。
您的描述缺乏很多精确性,但是这里有一些内容 :
sed -n -e '/^config/p;/item[45]/p;/^end/p' forti
config firewall address
edit "item4"
edit "item5"
end
编辑 :此答案是在需要保留item4
和item5
之后item4
next
行的编辑之前2小时给出的...
这可能对您有用(GNU sed):
sed '/config/,/end/!d;/config/b;/end/b;/item4/,+2b;/item5/,+2b;d' file
删除不在config
和end
之间的所有行。 打印以config
或end
开头的行以及以item4
或item5
以及以下两行。
这可能不是最好的方法,但是我找不到其他解决方法。
我将其范围缩小为四个命令,您可以将其放入bash脚本中(用您自己的源文件替换file.txt
,用所需的任何目标替换/tmp/finalFile
):
head -n1 file.txt >> /tmp/finalFile
head -n $(echo $(grep -ni item6 file.txt | cut -d: -f1) - 1 | bc) file.txt > /tmp/tmpfile
tail -n $(echo $(wc -l /tmp/tmpfile | awk '{print $1}') - $(grep -n item4 /tmp/tmpfile | cut -d: -f1) + 1 | bc) /tmp/tmpfile >> /tmp/finalFile
tail -n1 file.txt >> /tmp/finalFile
当我运行以上命令时,这是/tmp/finalFile
的最终文件:
config firewall address
edit "item4"
unset associated-interface
next
edit "item5"
unset associated-interface
next
end
一些解释:
head
finalFile
的第一行,附加到finalFile
item5
每一行,并将其保存在临时文件中。 tail
多少行,以使所有行达到item6
(不包括它),然后获取这些行,并将输出追加到finalFile
。 tail
finalFile
原始文件的最后一行,并将其追加到finalFile
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.