且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

sed 搜索并替换包含/的字符串

更新时间:2022-11-22 13:03:40

不要转义反斜杠;你会迷惑自己.在文本中没有出现的 s 命令之后使用不同的符号(我在下面的示例中使用了 %):

Don't escape the backslashes; you'll confuse yourself. Use a different symbol after the s command that doesn't appear in the text (I'm using % in the example below):

line_old='myparam /path/to/a argB=/path/to/B xo'
line_new='myparam /path/to/c argB=/path/to/D xo'
sed -i "s%$line_old%$line_new%g" /etc/myconfig

另外,用双引号将整个字符串括起来;使用单引号意味着 sed 看到的是 $line (在原始中)而不是扩展值.在单引号内,没有扩展,也没有元字符.如果您的文本几乎可以包含任何纯文本字符,请使用控制字符(例如 control-A 或 control-G)作为分隔符.

Also, enclose the whole string in double quotes; using single quotes means that sed sees $line (in the original) instead of the expanded value. Inside single quotes, there is no expansion and there are no metacharacters. If your text can contain almost any plain text character, use a control character (e.g. control-A or control-G) as the delimiter.

请注意,此处使用 -i 反映了问题中的内容,但前提是使用了 GNU sed.BSD sed(Mac OS X 上也有)需要一个后缀.可以使用 sed -i '' ... 原位替换;这不适用于 GNU sed.要在两者之间移植,请使用 -i.bak;这对两者都适用——但会给你一个你可能想要删除的备份文件.其他 Unix 平台(例如 AIX、HP-UX、Solaris)可能具有根本不支持 -ised 变体.sed的 POSIX 规范不需要它一>.

Note that the use of -i here mirrors what is in the question, but that assumes the use of GNU sed. BSD sed (found on Mac OS X too) requires a suffix. You can use sed -i '' … to replace in situ; that does not work with GNU sed. To be portable between the two, use -i.bak; that will work with both — but gives you a backup file that you'll probably want to delete. Other Unix platforms (e.g. AIX, HP-UX, Solaris) may have variants of sed that do not support -i at all. It is not required by the POSIX specification for sed.