代码之家  ›  专栏  ›  技术社区  ›  Bishwas Mishra

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

  •  -2
  • Bishwas Mishra  · 技术社区  · 8 年前
    $ 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 回复  |  直到 8 年前
        1
  •  1
  •   RavinderSingh13 Nikita Bakshi    8 年前

    跟随 awk 也可以帮你。

    awk -v line=2 '$1=="dog" && ++count==line{$1="big_dog"} 1'  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
  •  2
  •   James Brown    8 年前

    正如评论中所讨论的,这个替换了第二行的match:

    $ 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
    
        3
  •  1
  •   Hazzard17    8 年前

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

        4
  •  0
  •   Modassir Haider    8 年前

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

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

    如果要从第2个替换为第3个,则可以使用以下命令:

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