itsh itsh - 1 year ago 52
Bash Question

Find a string and replace the entire line for that string

I need to update the value of a specifc key (say,

) in the
file using shell command. I am trying to use
but it is working only if I have a specific value, for example,
in this case. But I want to update the value everytime irrespective of any value. Also my replacement string is stored in a variable. Can anybody suggest me what command shall I use?

hash.yaml file

key1: val1
key2: <TBD>
- val3_1
- val3_2

This is what I tried and works for me. But only if I have "TBD" as my search key.

sed -i "s;<TBD>;$var;g" hash.yaml

Answer Source

You can use this sed to replace any value of the key key2 with the new value stored in a variable called $var:


sed -E "s~^([ \t]*key2:[ \t]*).*~\1$var~" hash.yml

key1: val1
key2: foobar
 - val3_1
 - val3_2

In the expression ^([ \t]*key2:[ \t]*).* we match key2: at line start with optional whitespace before and after it. .* in the end will match anything for key2.

If you want to edit file in-place then use -i flag for sed:

sed -i '' -E "s~^([ \t]*key2:[ \t]*).*~\1$val~" hash.yml