Replace the string with a matching pattern with sed

I want to replace this line

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

with

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

20180305 is today when I save its value in a variable with

My approach

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

Where

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

which gives an error like this

sed: -e expression # 1, char 81: unknown parameter `s'

+4
source share
3 answers

Your team can be used to work with some changes in quoting and escaping:

$ 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"]

It looks like you want to change the last field in the rows that contain the row command:. In this case, the sed command may simplify:

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

Alternatively using 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
source

I recommend awk for this task.

You can replace the last field in real time by calling dateinsideawk

$ 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"]

+1

You can use the following command 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"]

where /.*command: \[ \"--no-save\", \"--no-restore\", \"--slave\", \".*work-daily.py\", \"20180212\"\]/used to find the correct line in the file, and s/20180212/$dated/used to replace.

0
source

Source: https://habr.com/ru/post/1694453/


All Articles