【问题标题】:Trouble altering a string in a variable with sed使用 sed 更改变量中的字符串时遇到问题
【发布时间】:2013-05-25 02:22:15
【问题描述】:

我正在尝试让 sed 更新 bash 脚本中的变量。这是我正在尝试做的一个简化示例。

myword="this is a test"
echo $myword
this is a test

换个工作测试

$myword | sed 's/a test/working'
echo $myword
this is working

【问题讨论】:

  • 试试 myword = cat $myword | sed ...
  • @AmirAfghani 你没有cat变量-你echo他们......
  • twalberg,我还没喝咖啡;)

标签: bash variables replace sed


【解决方案1】:

你需要终止你的正则表达式:

myword="this is a test"
myword=`echo $myword | sed 's/a test/working/'`
echo $myword

-> this is working

此外,您从未将输出重新分配回myword var。

【讨论】:

  • 您不需要在 myword 中执行分配吗?
  • 这是完美的。感谢您的帮助。
【解决方案2】:

为什么要麻烦使用sed。您可以使用 bash 字符串函数。

$ echo $myword
this is a test
$ echo ${myword/a test/working}
this is working

【讨论】:

    【解决方案3】:

    bash 中,您不需要sed 来执行此任务:

    $ myword="this is a test"
    $ myword=${myword/a test/working/'}
    $ echo $myword
    this is working
    

    如果您无法调整此解决方案,请发布您的实际用例。

    【讨论】:

      猜你喜欢
      • 2014-11-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-09
      • 2020-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多