Last active
September 12, 2018 03:07
-
-
Save vikyd/4acd26dcf42e44a4c8db1514ffb78a10 to your computer and use it in GitHub Desktop.
Shell: get value from key=value file with value trim and key trim, and allow `=` ` space` in value
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
# These vars and func are used to get value from a key=value file | |
# It will also trim the leading and trailing whitespace, tab | |
# Key with space after or before is supported | |
getVal(){ | |
# cut `=` in val: https://unix.stackexchange.com/a/53315/207518 | |
# grep: allow space after or before of key | |
# awk trim space after and before of value: https://unix.stackexchange.com/a/205854/207518 | |
declare val=$(cat ${1} | grep "^ *${2} *=" | cut -d '=' -f 2- | awk '{$1=$1}1') | |
# eval: https://unix.stackexchange.com/a/250178/207518 | |
eval ${3}=\$val | |
} | |
# Example | |
getVal keyval.txt key01 myVal | |
echo "|$val|" | |
echo "|$myVal|" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
abc=123 | |
akey01=4563456 | |
key01 = adsfadf 234 sfda @#$% sdafa;][34d= dsf asdf k-= 5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment