Reputation: 41
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's date where I am storing its value in a variable dated
My approach is
sed 's/.*command.*/"command: \[ "--no-save", "--no-restore", "--slave", "/home/app/src/work-daily.py", "$dated"\]"/' ghj.txt
where
dated=$(date +%Y%m%d)
its giving an error similar to this
sed: -e expression #1, char 81: unknown option to `s'
Upvotes: 4
Views: 233
Reputation: 3089
I'll recommend awk for this task
You can substitute the last field in real time by calling date
within 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;
: Date would get store in d
$NF=" \""d"\"]"
: Replacing last field with format "date"]
Upvotes: 1
Reputation: 113994
Your command can be made to work with some change in the 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 only want to change the last field on lines that include the string command:
. In that case, the sed command can simplify to:
$ 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"]
Upvotes: 1
Reputation: 12456
You can use the following sed
command:
$ 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\"\]/
is used to find the proper line in the file and s/20180212/$dated/
is used to do the replacement.
Upvotes: 0