Home > OS >  Linux: Set Variable to Value following regex pattern, without quotes, in a single command (no pipes)
Linux: Set Variable to Value following regex pattern, without quotes, in a single command (no pipes)

Time:08-22

I need to grab a value from a config file (config.toml) and store it to a system variable.

I prefer to use a single command without pipes in the most compatible way possible (across linux systems)

Should return https://abridge.netlify.app with the config file set any of these ways:

base_url="https://abridge.netlify.app"
base_url = "https://abridge.netlify.app"
base_url  =  "https://abridge.netlify.app"

The solution I have so far based on some research is the following:

baseurl="$(sed -n -E 's/^base_url.*=\s ?\"//p' config.toml)"
echo $baseurl

My solution still has the trailing quotation mark, I have not yet figured out how to deal with it.

The other problem is I am not certain that this is the most universal solution. I prefer to use something that will work universally on most linux systems.

Appreciate all feedback, Thank You!

CodePudding user response:

Different implementations of sed understand different types of regex. Only BRE is portable:

sed -n 's/^base_url[[:space:]]*=[[:space:]]*"\([^"]*\)".*/\1/p' config.toml

CodePudding user response:

Edit, based on @jhnc feedback. I now use this:

baseurl="$(sed -n -E 's/^base_url.*=.*"(.*)"/\1/p' config.toml)"
echo $baseurl

I am still not sure if some Linux systems might run into issues with this or not.

If anyone sees an issue with this solution or has a more universally compatible solution please let me know.

  • Related