$ cat file
cat cat
dog cat
dog puppy
dog cat
使用 sed:
$ sed 's/dog/big_dog/' my_file > new_file
$ cat new_file
cat cat
big_dog cat
big_dog puppy
big_dog cat
我的目标是只替换第二个dog
with big_dog
但这并没有发生:
$ sed 's/dog/big_dog/2' my_file > new_file
cat
dog cat
dog puppy
dog cat
我怎样才能只替换第二次出现的情况,即:
cat
dog cat
big_dog puppy
dog cat
sed
第二次出现的替换是:
sed "/dog/ {n; :a; /dog/! {N; ba;}; s/dog/big_dog/; :b; n; $! bb}" your_file
解释:
/dog/ { # find the first occurrence that match the pattern (dog)
n # print pattern space and read the next line
:a # 'a' label to jump to
/dog/! { # if pattern space not contains the searched pattern (second occurrence)
N # read next line and add it to pattern space
ba # jump back to 'a' label, to repeat this conditional check
} # after find the second occurrence...
s/dog/big_dog/ # do the substitution
:b # 'b' label to jump to
n # print pattern space and read the next line
$! bb # while not the last line of the file, repeat from 'b' label
}
请注意,在找到第二次出现后,需要最后 3 个命令来打印文件的其余部分,否则可能会对搜索模式的每个偶数出现重复替换。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)