【问题标题】:How to use a shell variable inside sed when doing "d" command?执行“d”命令时如何在 sed 中使用 shell 变量?
【发布时间】:2017-11-09 23:33:58
【问题描述】:

在我的 bash 中,我希望删除从 1 到 ${number} 的行,如下所示:

number=10
sed '1,${number}d' myfile

由于语法错误而失败。 我也试过 "\${number}", '"$number"',两者都不起作用


我改为双引号,它在命令行下工作,但不在 bash 脚本文件中。如何让它发挥作用?

【问题讨论】:

  • 您需要将变量放在引用的 sed 语句之外,因此:sed '1,'${number}'d' myfile
  • 显示您遇到的exact错误。

标签: bash variables sed line


【解决方案1】:

将您的 sed 表达式括在双引号中以插入变量 number:

sed "1,${number}d" file

【讨论】:

  • 谢谢,它可以在命令行下工作,但不能在 bash 脚本中工作。似乎 bash 脚本会执行 '1,$d' ,这将删除所有内容。
  • number 未在脚本中定义。
  • @HindForsum,将您的 bash 脚本的关键片段发布到您的问题中,以便我可以看到您的“sed”用法
【解决方案2】:

以这种方式运行 sed 时请使用双引号而不是单引号。 在这里阅读Difference between single and double quotes

【讨论】:

    【解决方案3】:

    我改成双引号,它在命令行下工作,但不在里面 bash 脚本文件

    假设你的 bash 脚本是:

    sed "1,${number}d" myfile
    

    您应该在 bash 提示符中导出 number 变量,以便在运行时在 bash 脚本中可见:

    export number=10
    

    【讨论】:

      猜你喜欢
      • 2018-09-16
      • 2014-04-24
      • 2022-01-08
      • 2015-08-10
      • 2017-07-10
      • 2017-10-03
      • 1970-01-01
      • 2013-10-09
      相关资源
      最近更新 更多