1

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
1
  • Sed is not the right tool to parse YAML Commented Oct 13, 2016 at 22:13

2 Answers 2

1

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 
Sign up to request clarification or add additional context in comments.

Comments

0

Using a proper YAML parser in (the right tool for the right job...) :

#!/usr/bin/perl

use Config::YAML;
use YAML::XS qw/DumpFile/;

my $ds = Config::YAML->new(
    config => "hash.yaml"
);

$ds->{key2} = 'FOOBAR';

DumpFile("./new.yaml", $ds);

then,

cat new.yaml

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.