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

zvms9eto  于 2023-04-11  发布在  Linux
关注(0)|答案(4)|浏览(911)
$ 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
ru9i0ody

ru9i0ody1#

就像在注解中讨论的那样,这个替换了第二行的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
pokxtpni

pokxtpni2#

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

3ks5zfa0

3ks5zfa03#

下面的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.
w9apscun

w9apscun4#

使用下面的命令将第二行中的单词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

相关问题