0

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?

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

4 Comments

$str in this case would be the file?
hm... using external grep and after bash builtin regex, instead of one external sed + read?
You could, but I find this a little simpler. It essentially uses a multi-character delimiter with password to separate the two values, rather than trying to come up with a safe single-character delimiter to use in IFS to let read resplit the output of sed.
As long as you could find a character that doesn't appear in the user (which in this case is probably trivial), something like IFS=% read user passwd < <(sed 's/create user (.*) with password (.*)/\1%\2/') would be fine. On the other extreme, you could even forgo the call to grep by using a while loop to read the file line by line, but I suspect grep would be faster unless you have a very small file or the line in question is found early. grep + =~ just happens to be (IMO) the simplest balance between two extremes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.