itsh itsh - 1 month ago 8
Bash Question

Find a string and replace the entire line for that string

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

key2
) in the
yaml
file using shell command. I am trying to use
sed
but it is working only if I have a specific value, for example,
TBD
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>
key3:
- 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

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

var='foobar'

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

key1: val1
key2: foobar
key3:
 - 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 
Comments