Reputation: 583
I'm trying to continue to extract and isolate sections of text within my wordpress config file via bash script. Can someone help me figure out my sytax?
The lineof code in the wp-config.php
file is:
$table_prefix = 'xyz_';
This is what I'm trying to use to extract the xyz_ portion.
prefix=$(sed -n "s/$table_prefix = *'[^']*'/p" wp-config.php)
echo -n "$prefix"
There's something wrong with my characters obviously. Any help would be much appreciated!
Upvotes: 1
Views: 317
Reputation: 11435
s/regex/replacement/p
to print your sed command. Yours, as written, will give unterminated 's' command
. If you want to print your whole line out, you can use the capture group \0
to match it as s/<our_pattern>/\0/p
$table_prefix
as a variable, and because it is in double quotes, it tries to expand it. Unless you set this variable to something, it expands to nothing. This would cause your sed command to match much more liberally, and we can fix it by escaping the $
as \$table_prefix
.=
, so we need another wildcard there as in ...prefix *= *...
xyz_
portion alone, we'll need to do some things. First, we have to make sure our pattern matches the whole line, so that when we substitute, the rest of the line won't be kept. We can do this by wrapping our pattern to match in ^.* ... .*\$
. Next, we want to wrap the target section in a capture group. In sed, this is done with \(<stuff>\)
. The zeroth capture group is the whole line, and then capture groups are numbered in the order the parentheses appear. this means we can do \([^']*\)
to grab that section, and \1
to output it:All that gives us:
prefix=$(sed -n "s/^.*\$table_prefix *= *'\([^']*\)'.*\$/\1/p" wp-config.php)
Upvotes: 3
Reputation: 3251
The only issue with the regex is that the '$' character specifies that you are using a bash variable and since the pattern is wrapped in double quotes ("
, bash will attempt to expand the variable. You can mitigate this by either escapping the $
or wrapping the pattern in single quotes and escaping the single quotes in the pattern
Lastly, you are using the sed
command s
which stands for subsitute. It takes a pattern and replaces the matches with text in the form of s/<pattern>/<replace>/
. You can omit the 's' and leave the 'p' or print command at the end. After all your command should look something like:
sed -n "/\$table_prefix = *'[^']*'/p" wp-config.php
Upvotes: -1