【问题标题】:I can't replace strings correctly with sed on terminal我无法在终端上用 sed 正确替换字符串
【发布时间】:2014-08-13 15:18:10
【问题描述】:

大家好,我关注了Find and Replace Inside a Text File from a Bash Command

现在我正在使用sed 解决方案,如果我使用两个预定义的字符串,它似乎可以工作,但我想用文件中的内容替换内容,而不是由我定义。

我有一个带有“功夫狗”字样的文件,我希望它用“熊猫”这个词替换“狗”这个词,但这个词在另一个文件中。我试着做:

sed -i 's/dog/$(cat filethatcontainspanda)/g' /home/myhome

但问题是,我没有将单词 dog 替换为 panda,而是将单词“dog”替换为“$(cat filethatcontainspanda)”,所以最后我没有使用“kung fu panda”,而是“功夫$(包含spanda的猫文件)”。有什么解决方法吗?

【问题讨论】:

  • 双引号试过了吗:sed -i "s/dog/$(cat filethatcontainspanda)/g" /home/myhome
  • 是的,解决了它,双引号工作正常,我第一次尝试双引号,就像这样 sed -i 's/dog/"$(cat filethatcontainspanda)"/g' /home/myhome它没有用,但非常感谢您的解决方案。
  • @user234688 单引号内的双引号没有特殊意义——你仍然在一个被保护不被扩展的字符串中。
  • 也可以将其完全排除在引号之外's/dog/'$(cat filethatcontainspanda)'/g'
  • variable in sed的可能重复

标签: linux bash sed scripting


【解决方案1】:

您需要使用双引号 " 而不是单引号 'awk 而不是 cat

sed -i "s/dog/$(awk '{print $1}' filethatcontainspanda)/g" /home/myhome

【讨论】:

  • 为什么是 awk?如果文件只包含一个单词,cat 就可以了。
【解决方案2】:

你必须使用 " 代替 '

sed -i "s/dog/$(cat filethatcontainspanda)/g" /home/myhome

【讨论】:

    猜你喜欢
    • 2014-05-20
    • 2020-07-28
    • 1970-01-01
    • 1970-01-01
    • 2020-03-13
    • 2014-09-16
    • 1970-01-01
    • 2012-12-21
    • 2021-03-01
    相关资源
    最近更新 更多