如何仅使用sed替换第二个匹配行

如何仅使用sed替换第二个匹配行

本文介绍了如何仅使用sed替换第二个匹配行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$ 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,但是这不会发生:

My objective is to replace only the second dog with big_dog but that's not happening with:

$ sed 's/dog/big_dog/2' my_file > new_file
cat
dog cat
dog puppy
dog cat

如何仅替换第二次出现的内容,即:

How to replace only the second occurrence, ie:

cat
dog cat
big_dog puppy
dog cat

推荐答案

遵循awk可能也可以为您提供帮助.

Following awk may also help you here.

awk -v line=2 '$1=="dog" && ++count==line{$1="big_dog"} 1'  Input_file

如果将输出保存到Input_file本身,则在上面的代码中附加> temp_file && mv temp_file Input_file.

In case of saving output into Input_file itself then append > temp_file && mv temp_file Input_file in above code.

说明:

Explanation:

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.

这篇关于如何仅使用sed替换第二个匹配行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 12:54