sed ' 在搜索模式中 $ 时替换文本
sed ' in replacement text when $ in search pattern
我有一个包含字符串 "this $c$ is a single quote" 的文件,创建如下:
%echo "this $c$ is a single quote" > test3.txt
%cat test3.txt
this $c$ is a single quote
我想用单引号替换字母 c,但我还需要匹配 $ 字符(以避免匹配其他字符 'c')。我好像做不到。
我试过了
%sed 's/$c$/$foo$/' test3.txt
this $c$ is a single quote
所以显然我需要转义 $.
%sed 's/$c$/$foo$/' test3.txt
this $foo$ is a single quote
但是当我尝试在替换文本中放入转义的 ' 时,我得到
%sed 's/$c$/$\'$/' test3.txt
quote>
所以我需要使用其他一些引用方法。
%sed "s/$c$/$'$/" test3.txt
this $c$ is a single quote
没有任何内容被替换,所以我们尽量不要转义 $
%sed "s/$c$/$'$/" test3.txt
this $c$ is a single quote$'$
这出乎我的意料,所以让我们尝试只匹配 c
作为完整性检查。
%sed "s/c/'/" test3.txt
this $'$ is a single quote
我尝试了一些其他组合,但没有成功。我如何在 sed
中执行此操作?
这个怎么样?
!$ echo 'This is $c$ ceee' | sed s/\$c\$/\'/
This is ' ceee
我没有用引号将整个 sed 命令括起来,所以我需要分别转义每个反斜杠和每个美元(当然还有引号)。
编辑
正如 Chris Lear 指出的那样,我的替换字符串不包含美元。这是一个修复 - 请注意 这些 美元对 sed
没有特殊含义(它们不被解释为匹配符号,它们只是要插入的普通字符) 所以它们只能被转义一次:
!$ echo 'This is $c$ ceee' | sed s/\$c\$/\$\'\$/
This is $'$ ceee
!$ echo 'This is $c$ ceee' | sed s/\$c\$/$\'$/
This is $'$ ceee
如果你想引用 sed
命令你需要做大量的转义。 $
是 shell 和 sed
模式的特殊字符。在 shell 中,它表示要扩展的变量名的开头,在您的情况下为 $c
。到sed
表示行尾。要进行引用,您需要将其从两者中转义,这样您就可以
sed "s/\$c\$/$'$/" test3.txt
或者您可以混合引用样式,在 $ 扩展周围使用单引号,在单引号周围使用双引号,例如
sed 's/$c$/$'"'"'$/' test3.txt
你可以使用ansi c字符串
sed $'s/$c$/\'/'
这允许 $
s 和 '
s 的单个反斜杠转义。
如果你想保留$
s
sed $'s/$c$/$\'$/'
试试这个:
sed -i -E "s/([$]c[$])/\'/g" sed.txt
我有一个包含字符串 "this $c$ is a single quote" 的文件,创建如下:
%echo "this $c$ is a single quote" > test3.txt
%cat test3.txt
this $c$ is a single quote
我想用单引号替换字母 c,但我还需要匹配 $ 字符(以避免匹配其他字符 'c')。我好像做不到。
我试过了
%sed 's/$c$/$foo$/' test3.txt
this $c$ is a single quote
所以显然我需要转义 $.
%sed 's/$c$/$foo$/' test3.txt
this $foo$ is a single quote
但是当我尝试在替换文本中放入转义的 ' 时,我得到
%sed 's/$c$/$\'$/' test3.txt
quote>
所以我需要使用其他一些引用方法。
%sed "s/$c$/$'$/" test3.txt
this $c$ is a single quote
没有任何内容被替换,所以我们尽量不要转义 $
%sed "s/$c$/$'$/" test3.txt
this $c$ is a single quote$'$
这出乎我的意料,所以让我们尝试只匹配 c
作为完整性检查。
%sed "s/c/'/" test3.txt
this $'$ is a single quote
我尝试了一些其他组合,但没有成功。我如何在 sed
中执行此操作?
这个怎么样?
!$ echo 'This is $c$ ceee' | sed s/\$c\$/\'/
This is ' ceee
我没有用引号将整个 sed 命令括起来,所以我需要分别转义每个反斜杠和每个美元(当然还有引号)。
编辑
正如 Chris Lear 指出的那样,我的替换字符串不包含美元。这是一个修复 - 请注意 这些 美元对 sed
没有特殊含义(它们不被解释为匹配符号,它们只是要插入的普通字符) 所以它们只能被转义一次:
!$ echo 'This is $c$ ceee' | sed s/\$c\$/\$\'\$/
This is $'$ ceee
!$ echo 'This is $c$ ceee' | sed s/\$c\$/$\'$/
This is $'$ ceee
如果你想引用 sed
命令你需要做大量的转义。 $
是 shell 和 sed
模式的特殊字符。在 shell 中,它表示要扩展的变量名的开头,在您的情况下为 $c
。到sed
表示行尾。要进行引用,您需要将其从两者中转义,这样您就可以
sed "s/\$c\$/$'$/" test3.txt
或者您可以混合引用样式,在 $ 扩展周围使用单引号,在单引号周围使用双引号,例如
sed 's/$c$/$'"'"'$/' test3.txt
你可以使用ansi c字符串
sed $'s/$c$/\'/'
这允许 $
s 和 '
s 的单个反斜杠转义。
如果你想保留$
s
sed $'s/$c$/$\'$/'
试试这个:
sed -i -E "s/([$]c[$])/\'/g" sed.txt