使用sed替换具有匹配模式的行

问题描述 投票:4回答:3

我想替换这一行

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是今天我将其价值存储在变量日期中的日期

我的方法是

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表达式#1,char 81:`s'的未知选项

linux bash sed
3个回答
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"]

1
投票

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

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

$ 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"]替换最后一个字段


0
投票

您可以使用以下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/用于替换。

© www.soinside.com 2019 - 2024. All rights reserved.