Closed. This question needs details or clarity。它当前不接受答案。
想改善这个问题吗?添加详细信息并通过editing this post阐明问题。
2年前关闭。
使用sed:
我的目标是仅用
如何仅替换第二次出现,即:
如果将输出保存到Input_file本身,则在上述代码中附加
说明:
想改善这个问题吗?添加详细信息并通过editing this post阐明问题。
2年前关闭。
$ 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
替换第二个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
最佳答案
跟随awk
可能也可以帮助您。
awk -v line=2 '$1=="dog" && ++count==line{$1="big_dog"} 1' Input_file
如果将输出保存到Input_file本身,则在上述代码中附加
> temp_file && mv temp_file Input_file
。说明:
awk -v line=2 ' ##Creating an awk variable line whose value is 2 here.
$1=="dog" && ++count==line{ ##Checking condition if $1 is dog and increasing variable count value is equal to value of line(then do following)
$1="big_dog"} ##Assigning $1 to big_dog here.
1 ##awk works on method of condition then action so by mentioning 1 I am making condition TRUE here so by default action print of line will happen.
' Input_file ##Mentioning Input_file here.
10-07 16:38