【问题标题】:Replace a line with a matching pattern using sed使用 sed 将一行替换为匹配的模式
【发布时间】:2018-08-12 19:18:50
【问题描述】:

我想替换这一行

command: [ "--no-save", "--no-restore", "--slave", "/home/app/src/work-daily.py", "20180212"]

command: [ "--no-save", "--no-restore", "--slave", "/home/app/src/work-daily.py", "20180305"]

20180305 是今天的日期,我将其值存储在变量 dated 中

我的方法是

sed 's/.*command.*/"command: \[ "--no-save", "--no-restore", "--slave", "/home/app/src/work-daily.py", "$dated"\]"/' ghj.txt

在哪里

dated=$(date +%Y%m%d)

它给出了一个类似的错误

sed: -e expression #1, char 81: `s' 的未知选项

【问题讨论】:

标签: linux bash sed


【解决方案1】:

您的命令可以在引用和转义中进行一些更改:

$ sed 's/.*command.*/command: \[ "--no-save", "--no-restore", "--slave", "\/home\/app\/src\/work-daily.py", "'"$dated"'"\]/' ghj.txt
command: [ "--no-save", "--no-restore", "--slave", "/home/app/src/work-daily.py", "20180305"]

您似乎只想更改包含字符串 command: 的行上的最后一个字段。在这种情况下,sed 命令可以简化为:

$ sed -E "/command:/ s/\"[[:digit:]]+\"\]/\"$dated\"]/" ghj.txt
command: [ "--no-save", "--no-restore", "--slave", "/home/app/src/work-daily.py", "20180305"]

或者,使用 awk:

$ awk -F\" -v d="$dated" '/command:/{$10=d} 1' OFS=\" ghj.txt
command: [ "--no-save", "--no-restore", "--slave", "/home/app/src/work-daily.py", "20180305"]

【讨论】:

    【解决方案2】:

    您可以使用以下sed 命令:

    $ cat input; dated=$(date +%Y%m%d); sed "/.*command: \[ \"--no-save\", \"--no-restore\", \"--slave\", \".*work-daily.py\", \"20180212\"\]/s/201
    80212/$dated/" input                                                                                                                         
    command: [ "--no-save", "--no-restore", "--slave", "/home/app/src/work-daily.py", "20180212"]
    command: [ "--no-save", "--no-restore", "--slave", "/home/app/src/work-daily.py", "20180305"]
    

    其中/.*command: \[ \"--no-save\", \"--no-restore\", \"--slave\", \".*work-daily.py\", \"20180212\"\]/ 用于在文件中查找正确的行,s/20180212/$dated/ 用于进行替换。

    【讨论】:

      【解决方案3】:

      我会推荐 awk 来完成这项任务

      您可以通过在awk 中调用date 来实时替换最后一个字段

      $ awk -F, -v OFS=, 'BEGIN{"date +%Y%m%d" | getline d} {$NF=" \""d"\"]"}1' file
      command: [ "--no-save", "--no-restore", "--slave", "/home/app/src/work-daily.py", "20180305"]
      

      "date +%Y%m%d" | getline d;:日期将存储在d

      $NF=" \""d"\"]":用"date"]格式替换最后一个字段

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-07-24
        • 2016-12-17
        • 1970-01-01
        • 2021-04-02
        • 1970-01-01
        • 1970-01-01
        • 2021-03-15
        相关资源
        最近更新 更多