Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash 如何用sed查找并替换前n个外观?_Bash_Sed - Fatal编程技术网

Bash 如何用sed查找并替换前n个外观?

Bash 如何用sed查找并替换前n个外观?,bash,sed,Bash,Sed,我一直在使用此代码替换文件中第一个出现的模式: sed "0,\#pattern#s##replacement#" input.txt > output.txt 为了替换文件中模式的前5次出现,我使用了以下方法: sed "0,\#pattern#s##replacement#" input.txt > output1.txt sed "0,\#pattern#s##replacement#" output1.txt > output2.txt sed "0,\#patter

我一直在使用此代码替换文件中第一个出现的模式:

sed "0,\#pattern#s##replacement#" input.txt > output.txt
为了替换文件中模式的前5次出现,我使用了以下方法:

sed "0,\#pattern#s##replacement#" input.txt > output1.txt
sed "0,\#pattern#s##replacement#" output1.txt > output2.txt
sed "0,\#pattern#s##replacement#" output2.txt > output3.txt
sed "0,\#pattern#s##replacement#" output3.txt > output4.txt
sed "0,\#pattern#s##replacement#" output4.txt > output5.txt
mv output5.txt output.txt

我怎样才能更简单地用sed替换匹配的第一个
n
外观?

sed
没有自然计数能力。你可以做一些像这样奇怪的事情

sed -r '
  /pattern/ {
    s//replacement/
    x
    s/.*/&x/ 
    t clear
    : clear
    s/x{3}/&/
    x
    T
    q
  }
' file
在最后一个替换命令中,将
x
的数量设置为所需的替换数量。实际上,此命令需要与
-i
一起使用,以就地修改文件,因为它在执行请求的替换次数后退出并停止处理文件

以上评论如下:

sed -r '
  /pattern/ {
    s//replacement/
    x          # exchange spaces
    s/.*/&x/   # increment number of x s
    t clear    # reset the successul substitition flag
    : clear    
    s/x{3}/&/  # test for the required number of x s to quit
    x          # exchange spaces
    T          # if substitution was not successful, next cycle
    q          # quit
  }
' file
这里有另一个想法,但最多只能更换10个

sed -r '
  1{x;s/^/0/;x}
  /pattern/ {
    s//replacement/
    x
    y/0123456789/1234567890/
    tx :x   # reset substitution flag
    s/3/&/
    x; T; q
}'
如果您使用的
sed
没有
t
命令,则可以将其替换为相反的
t
命令。更改:

T
q


也可以考虑Perl:

perl -lpe 's#pattern#s##replacement# and $n++ if $n < 5' input
perl-lpe的#模式#s#替换#和$n++如果$n<5'输入

对于
sed
(我个人使用了
awk
)来说,这并不是一个自然的工作,但以下几点应该可以:

 sed '1{x;s/.*/00000/;x};/PATTERN/{x;s/0//;x;t1;b;:1;s/PATTERN/REPLACEMENT/}'
第一个
s
命令中
0
s字符串的长度是替换次数;我使用
0
的目的是生成
sed
命令,如下所示:

 sed "1{x;s/.*/$(printf %*d $COUNT 0)/;x};
     /$PATTERN/{x;s/0//;x;t1;b;:1;s/$PATTERN/$REPLACEMENT/}"
使用Gnu
sed
,您可以替换
t1;b、 :1;
T

以下是awk版本:

 awk 'N&&sub(PAT,REPL){N--};1' N=5 PAT="pattern" REPL="replacement"
现在有办法了!
 awk 'N&&sub(PAT,REPL){N--};1' N=5 PAT="pattern" REPL="replacement"