【问题标题】:How to echo a special character into a file?如何将特殊字符回显到文件中?
【发布时间】:2018-02-15 15:40:54
【问题描述】:

我有一个可以做各种事情的 shell 脚本。

其中,它检查/etc/rc.local中是否存在某行,如果该行不存在,我想将其添加到文件中。

grep reboot "/etc/rc.local" || echo -e "sed -i 's/\^reboot//g' $script" >> /etc/rc.local

问题是我无法在文件中插入特殊字符“^”。

所以如果我只是运行该行,而不重定向到 /etc/rc.local:

# grep reboot  "/etc/rc.local" || echo -e 'sed -i "s/\^reboot//g" $script' >> /etc/rc.local
sed -i 's/reboot//g' /root/1.sh

您可以看到回显的行错过了“^”。

我尝试过使用和不使用 echo 的“-e”开关,尝试使用双引号/单引号...没有任何效果 - 我似乎无法回显特殊字符。

我做错了什么?

【问题讨论】:

  • reboot相比,为什么在任何脚本中都需要^reboot
  • 此脚本升级内核,然后重新启动并继续运行。 /etc/rc.local 中的这一行应该在再次运行以完成其余任务之前从脚本中删除“重启”命令——这样做是为了避免进入重启循环。我希望该命令仅删除脚本中包含重新启动命令的行,因此将“^”作为重新启动命令本身在该行中。脚本中还有其他地方需要重新启动,但我不想触及其他行,只有实际重新启动的那一行。
  • 我的问题仍然存在,为什么是文字 ^reboot ?还是您正在寻找行中只有reboot 而没有其他内容的行?
  • 完全正确 - 只有一行只包含重新启动,这就是我要删除的行。

标签: bash sed echo special-characters


【解决方案1】:
$ cat inputfile
some reboot
reboot
some reboot other

删除只有reboot 而没有其他内容的行。

$ sed '/^reboot$/d' inputfile
some reboot
some reboot other

使用-i 将其就地删除并覆盖inputfile

【讨论】:

    【解决方案2】:

    要删除以“rebo​​ot”开头的行,请使用

    grep -v '^reboot' /etc/rc.local > result
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-25
      • 2019-04-07
      • 2018-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-12
      • 1970-01-01
      相关资源
      最近更新 更多