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

时间:2018-05-31 12:45:07

标签: linux unix 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,但这不会发生:

$ 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

4 个答案:

答案 0 :(得分:2)

就像在评论中讨论的那样,这个替换了第二行的匹配:

$ sed '2s/dog/big_dog/' your_file
dog cat
big_dog puppy
dog cat

要用sed替换第二个匹配项,请使用:

sed ':a;N;$!ba;s/dog/big_dog/2'   your_file_with_foo_on_first_row_to_demonstrate
foo
dog cat
big_dog puppy
dog cat

答案 1 :(得分:1)

关注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.

答案 2 :(得分:1)

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个命令来打印文件的其余部分,否则可能会对搜索到的模式的每个偶数事件重复替换。

答案 3 :(得分:0)

使用以下命令将第二行中的单词dog替换为big_dog。

# sed -i '2 s/dog/big_dog/g' my_file
# cat my_file
Output:-
dog cat
big_dog puppy
dog cat

相同如果你想从第二个到第三个替换,那么你可以使用以下命令: -

# sed -i '2,3 s/dog/big_dog/g' my_file