sed命令用特殊字符替换带有特殊字符的字符串

时间:2022-11-16 16:52:59

I have a string with special characters called /data/user/sam and I want to replace it with /data/sam and write it in a text file called sample.txt. I am able to do so but it keeps on appending the result in sample.txt on running the command again. It should replace it whole each time instead of appending.

我有一个名为/ data / user / sam的特殊字符的字符串,我想用/ data / sam替换它,并将其写入名为sample.txt的文本文件中。我能够这样做,但它继续将结果附加到sample.txt上再次运行命令。它应该每次都替换它而不是附加。

Here is the snippet:-

这是片段: -

sed 's/"\/data\/user\/sam"/"\/data\/sam"/g' sample.txt

Output in sample.txt on running twice

在运行两次时在sample.txt中输出

/data/sam/data/sam

It should be:

它应该是:

/data/sam 

on running as many times as user wants.

根据用户的需要运行多次。

1 个解决方案

#1


You can specify the delimiter of the pattern (here I choose #, which may not * with pathnames):

您可以指定模式的分隔符(这里我选择#,它可能不与路径名冲突):

sed 's#/data/user/sam#/data/sam#g' sample.txt

Use option -i to perform in-place substitution.

使用选项-i执行就地替换。

#1


You can specify the delimiter of the pattern (here I choose #, which may not * with pathnames):

您可以指定模式的分隔符(这里我选择#,它可能不与路径名冲突):

sed 's#/data/user/sam#/data/sam#g' sample.txt

Use option -i to perform in-place substitution.

使用选项-i执行就地替换。