我该怎么办?我有多个,例如我文件中的foobar模式,我怎样才能添加第四个some_text?
答案 0 :(得分:1)
以下是否适用于您?
sed ':a;$!{N;ba};s/\(foobar\)/\1\nsome_text/4' inputfile
输入:
$ cat inputfile
line
foobar
foobar
foobar
line
foobar
line
foobar
line
foobar
line
这将生成
$ sed ':a;$!{N;ba};s/\(foobar\)/\1\nsome_text/4' inputfile
line
foobar
foobar
foobar
line
foobar
some_text
line
foobar
line
foobar
line
在FreeBSD上使用-e
:
sed -e :a -e '$!N' -e '$!ba' -e 's/\(foobar\)/\1\nsome_text/4' inputfile
答案 1 :(得分:1)
awk版本:
awk '/foo/{x++} x==4{sub(/foo/,"&some_text")}1' file
示例:
kent$ cat file
foo
foo
trash
foo
trash
foo
foo
foo
kent$ awk '/foo/{x++} x==4{sub(/foo/,"&some_text")}1' file
foo
foo
trash
foo
trash
foosome_text
foo
foo