Reputation: 139
I have a bash script that I am trying to learn from. I have a sql file that has in it:
create user myuser with password 'mypassword';
I want to use sed and store the value of the password in one bash variable and the pasword in another bash variable. The script that I am learning from has:
USERNAME := $(shell sed -n \
"s/^create user \(\S\+\) with password '\(\S\+\)';$$/\1/p" \
createdb.sql)
PASSWORD := $(shell sed -n \
"s/^create user \(\S\+\) with password '\(\S\+\)';$$/\2/p" \
createdb.sql)
No matter what I tried the regex would not match up. Part of my issue is I don't understand the basics of sed. How do I go about getting the value of parts of the string?
Upvotes: 0
Views: 108
Reputation: 532238
Don't use sed
for this; use bash
's built-in regular expression support.
str="create user myuser with password 'mypassword';"
regex='create user (.*) with password (.*);'
if [[ $str =~ $regex ]]; then
username=${BASH_REMATCH[1]}
password=${BASH_REMATCH[2]}
fi
As for how you get the appropriate line in the first place, use grep
:
str=$(grep "create user" createddb.sql)
Upvotes: 2