Parsing key=value pairs in bash
Here's a neat text processing trick for Bash. Let's say you have a text file in which you want to replace several words with new words. The words and their replacements are supplied to you as key=value pairs. How can you parse the pairs?
It turns out the set built-in command will set the shell's positional arguments using the positional arguments you give it. For example:
set foo bar baz echo $1 $2 $3
This would print foo bar baz. You can use this with a command like tr that splits text.
Here's a longer example. This code will replace all occurrences of "foo", "bar", and "baz" with "red", "green", and "blue", respectively, in "somefile.txt".
changes="foo=red bar=green baz=blue"
for change in $changes; do
set -- `echo $change | tr '=' ' '`
old=$1
new=$2
sed -i -e "s/$old/$new/g" somefile.txt
done
For the set command, we echo a key=value pair to tr which replaces the delimiter with a space. This gives set two positional arguments, which are assigned to $1 and $2.
RSS feed