Linux shell get value of a field from a yml file

That is fairly easy, not using sed, but with appropriate shell tools. First, if you need to preserve sample in a variable for later use, then something like the following will work using bash substring replacement to isolate sample on the Test:/database: line:

$ db=$(grep -A3 'test:' database.yml | tail -n1); db=${db//*database: /}; echo "$db"
sample

or for a shorter solution that you can dump to the command line, remove the variable and command substitution and use a tool like cut:

$ grep -A3 'test:' database.yml | tail -n1 | cut -c 13-
sample

or, with awk, simply:

$ grep -A3 'test:' database.yml | tail -n1 | awk '{ print $2}'
sample

All of the different ways can be used inside command substitution (i.e. var=$(stuff) ) to store sample in var, it is just a matter of which you would rather use. I think you get the idea.


There are better tools than sed. You might be stuck on a minimal system, but other people looking for an answer probably won't be.

The python version of yq acts like jq:

$ pip3 install yq
$ yq -r .test.database database.yml
sample

shyaml works too, but has an odd restriction that you can only redirect into it:

$ pip3 install shyaml
$ shyaml get-value test.database < database.yml
sample

If perl is around and you have YAML installed:

$ cpan YAML
$ perl -MYAML -le 'print YAML::LoadFile(shift)->{test}{database}' database.yml
sample

Or, if you want ruby:

$ ruby -r yaml -e 'puts YAML.load_file(ARGV[0])["test"]["database"]' database.yml
sample

Tags:

Linux

Shell

Yaml