str='-e ENV_PASSWORD="foo" -e ENV_USER="bar-e sd" -e ENV_DB_NAME="mysite_staging" '
I need to retrieve the environment variable name in one variable and its value in another from the above string using a Bash script.
I tried the below code in Python which works in python3 but the same pattern is not working with grep
:
File: python_test.py
import re
str='-e ENV_PASSWORD="foo" -e ENV_USER="bar-e sd" -e ENV_DB_NAME="mysite_staging" '
re_pattern='-e\s+(.*?)="(.*?)"'
rec_pattern = re.compile(re_pattern, re.VERBOSE)
res = rec_pattern.findall(str)
for x in res:
print(f'Name="{x[0]}" Value="{x[1]}"')
--------------
Output:
Name="ENV_PASSWORD" Value="foo"
Name="ENV_USER" Value="bar-e sd"
Name="ENV_DB_NAME" Value="mysite_staging"
File: bash_test.sh
#!/bin/bash
str='-e ENV_PASSWORD="foo" -e ENV_USER="bar -e sd" -e ENV_DB_NAME="mysite_staging" '
re_pattern='-e\s+(.*?)="(.*?)"'
array=( $(grep -oP $re_pattern <<<$str) )
for i in ${array[@]}; do
echo $i;
done