Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux shell get value of a field from a yml file

Tags:

yaml

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 value of database of test environment (that is sample for the YAML shown). How can we do that using sed?

like image 231
Naveen Kumar Avatar asked Apr 30 '15 13:04

Naveen Kumar


People also ask

How do I view a YML file in Linux?

yml files you have to install and use Docker Compose. After the installation, go to your docker-compose. yml directory and then execute docker-compose up to create and start services in your docker-compose. yml file.

Does jq work with YAML?

a lightweight and portable command-line YAML processor. yq uses jq like syntax but works with yaml files as well as json.

How do I access a YML file?

How to open a YML file. You can open a YML file in any text editor, such as Microsoft Notepad (Windows) or Apple TextEdit (Mac). However, if you intend to edit a YML file, you should open it using a source code editor, such as Microsoft Visual Studio Code (cross-platform) or GitHub Atom (cross-platform).

What is YQ command?

yq is a command-line tool designed to transform YAML. It is similar to jq which focuses on transforming JSON instead of YAML.


1 Answers

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.

like image 193
David C. Rankin Avatar answered Oct 04 '22 05:10

David C. Rankin