Linux shell get field value from yml file
I have a database.yml file like
development:
adapter: mysql2
encoding: utf8
database: d360
host: localhost
username: root
password: password
test:
adapter: mysql2
encoding: utf8
database: sample
host: localhost
username: root
password: password
Now I want the value of the test environment database (that is, sample
for the YAML shown). How can we do this with sed?
source to share
It's pretty easy without using sed
but with the appropriate shell tools. First, if you need to store sample
in a variable for later use, then something like the following will work using bash substring substitution to isolate sample
from Test: / database ::
$ db=$(grep -A3 'test:' database.yml | tail -n1); db=${db//*database: /}; echo "$db"
sample
or for a shorter solution that you can dump on 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, << 26>, simply:
$ grep -A3 'test:' database.yml | tail -n1 | awk '{ print $2}'
sample
All the different ways can be used inside command substitution (i.e. var=$(stuff)
) to store sample
in var
, it's just the question you would rather use. I think you get the idea.
source to share
YAML is clearly not wrapped around. But sed is not a YAML parser either. Also no grep, tail, cut, etc. I'm sure you need a real language in which to write the correct parser. Awk, perl, python, erlang, etc.
You can use sed or shell or somesuch if you know your YAML data will always be formatted in a certain way, or will contain certain values ββin a certain order, but to make the parser work in general and on whatever ol 'YAML you point it to , you will need to emulate parsers that already exist in other languages.
If you don't want to write your own (maybe ask the StackOverflow community for help after you have some code to consider), then one option might be to install a tool like shyaml that can parse files accurately and give you authoritative content. A fast solution, easy to implement in your scripts, although it has some dependencies (python).
source to share