我在 Mac OS X 上使用 sed 替换字符串有什么问题?

What is wrong with my string substitution using sed on Mac OS X?

我想用 /etc/sshd_config 中的 Banner /etc/sshd_banner 替换 #Banner none。如果我运行

sudo sed -i "s/#Banner none/Banner \/etc\/sshd_banner" /etc/sshd_config

我收到以下错误

sed: 1: "/etc/sshd_config": unterminated substitute pattern

关于如何解决这个问题有什么想法吗?

Use another delimiter

请注意,我确实使用 " 作为分隔符

sudo sed -i "" "s|#Banner none|Banner /etc/sshd_banner|" /etc/sshd_config

通过更改分隔符,您无需转义 /

你原来的post最后漏了一个/

来自 OS X 手册

-i extension
         Edit files in-place, saving backups with the specified extension.  If a zero-length extension
         is given, no backup will be saved.  It is not recommended to give a zero-length extension when
         in-place editing files, as you risk corruption or partial content in situations where disk
         space is exhausted, etc.

zero-length = ""

您的命令存在三个问题:

  1. 您缺少终止符 /
  2. 无论如何你都不能使用/作为分隔符,因为这个字符出现在你试图replace/substitute的字符串中。您应该使用不同的字符(例如竖线字符)作为分隔符。
  3. 在 Mac OS X 附带的 sed 版本 (BSD) 中,-i 标志需要一个 强制性 <extension> 参数,你的命令丢失了。如果要使用此版本的 sed.
  4. 就地编辑文件,则空字符串 ("") 应跟在 -i 标志之后

综上所述,尝试

sudo sed -i "" "s|#Banner none|Banner /etc/sshd_banner|" /etc/sshd_config

试试单引号。此外,如果您想使用 /.

以外的内容,一些 Seds 要求您转义第一个定界符
sudo sed -i 's\:#Banner none:Banner :etc/sshd_banner:' /etc/sshd_config

另一件事是 # 可能被解释为一直到行尾的注释。