Using xq
(from https://kislyuk.github.io/yq/) to just get those strings out:
#!/bin/shset -- \ config/global/resources/default_setup/connection/host \ config/global/resources/default_setup/connection/username \ config/global/resources/default_setup/connection/password \ config/global/resources/default_setup/connection/dbnameIFS=:xq -r --arg path_string "$*" \'getpath(($path_string | split(":") | map(split("/")))[])' file.xml
This gives the path expressions to xq
as a :
-delimited list in the variable $path_string
. This string is subsequently split into its constituent paths, and these are then further split into path elements, so that one path internally may look like
["config","global","resources","default_setup","connection","dbname"]
The path arrays are given to the getpath()
function which extracts the values located at those paths.
The output, for the given XML document, will be
localhostrootpass123testdb
Creating shell assignment statements instead:
#!/bin/shset -- \ config/global/resources/default_setup/connection/host \ config/global/resources/default_setup/connection/username \ config/global/resources/default_setup/connection/password \ config/global/resources/default_setup/connection/dbnameeval "$( IFS=: xq -r --arg path_string "$*" ' ($path_string | split(":") | map(split("/"))[]) as $path |"\($path[-1])=\(getpath($path)|@sh)"' file.xml)"printf 'host = "%s"\n'"$host"printf 'user = "%s"\n'"$username"printf 'pass = "%s"\n'"$password"printf 'database = "%s"\n'"$dbname"
For the given paths and XML document, the xq
statement above would create the output
host='localhost'username='root'password='pass123'dbname='testdb'
This would be safe to eval
to assign the host
, username
, password
, and dbname
shell variables.
The output of the script would be
host = "localhost"user = "root"pass = "pass123"database = "testdb"