Reputation: 33
I want to replace the last word of the line only if a matching string found.
Input file :
"id": 5918915,
"description": "Test Job - NA",
"revision": 5
Expected output :
"id": 5918915,
"description": "Test Job - EU",
"revision": 5
So, for lines matching description
, replace the last word with given word. In this case, in line 2 replace last word NA",
with EU",
I tried
sed -i '/"description"/s/.*/EU",//g' file_name
but it is not working
Upvotes: 2
Views: 2006
Reputation: 33
I got the working command
sed -i '/"description"/ s/[^ ]* *$/EU",/' file_name
Upvotes: 1
Reputation: 36229
sed -i -r '/^[ \t]*"description":.*/s/^(.* )NA",[\t ]*$/\1EU/' FILE
"id": 5918915,
"description": "Test Job - EU",
"revision": 5"
For testing, remove the -i switch.
The amount of whitespace isn't quiet clear, so I placed [ \t]*
at line start and end for blanks and tabs of random size.
Your command:
sed -i '/"description"/s/.*/EU",//g' file_name
should substitute the whole line with EU",
, not just the last char sequence.
The -i is an option of GNU-sed. Check your version and read the fine manual. If your sed lacks support, you have to redirect the output to a file sed "COMMANDS" INFILE > TMPFILE; mv TMPFILE INFILE
. Note, that sed "COMMANDS" INFILE > INFILE
will not work, but destroy the INFILE immediately; a popular, clever, but disfunctional idea. I had it too. :)
Upvotes: 2