Reputation: 881
I'm currently writing a script to mass reset wordpress username and passwords. The passwords were stored using old-passwords and now with an update to MySQL and PHP, the old passwords are no longer working and hence need to be reset.
I have a file that looks like this:
define('DB_USER', 'abc_12345');
define('DB_PASSWORD', 'abc12345');
define('DB_USER', 'def_34589');
define('DB_PASSWORD', 'def34589');
I'm just needing to return the values inside the single quotes:
DB_USER abc_12345
DB_PASSWORD abc12345
DB_USER def_34589
DB_PASSWORD def34589
Now, I've looked around at the similar questions, but they all are a bit different then what I'm working with.
I've tried the following:
cat file.txt | awk '{print $1,$2}'
which returns
define('DB_USER', 'abc_12345');
define('DB_PASSWORD', 'abc12345');
define('DB_USER', 'def_34589');
define('DB_PASSWORD', 'def34589');
I've tried
cat file.txt | awk '{print $1}'
which returns
define('DB_USER',
define('DB_PASSWORD',
I've tried
cat file.txt | awk '{print $2}'
which returns
'abc_12345');
'abc12345');
I've also tried awk mixed with grep
cat file.txt | awk '{print $2}' | grep -P " '*.' "
which doesn't return anything.
Upvotes: 4
Views: 7965
Reputation: 196
I was able to accomplish this in Cygwin the following way...
$ cat test.file | awk -F "\'" '{print $2" "$4}'
DB_USER abc_12345
You might get an awk warning because of the escapes, however the output should be exactly what you were wanting using similar syntax to what you already tried. I found that using double-quotes, at least in my shell, around a single-quote delimiter works well as long as you escape the single in the middle. For the output field of awk however you want to switch back to the single-quotes, otherwise you will have errors like this...
$ cat test.file | awk -F "\'" "{print $2" "$4}"
awk: cmd. line:1: {print
awk: cmd. line:1: ^ unexpected newline or end of string
As an aside, I understand using cat is not as efficient as awk by itself, but very often I build one liners like this using cat, trimming output up as I go. If I were to script this out, I would consider a more efficient method, but if I'm generating a one-time report, it makes no difference to me.
Upvotes: 0
Reputation: 85795
If you have GNU grep
:
$ grep -Po "(?<=')[^',]+(?=')" file | xargs -n2
DB_USER abc_12345
DB_PASSWORD abc12345
DB_USER def_34589
DB_PASSWORD def34589
This greps for anything inside single quotes that isn't a '
or ,
then xargs
just group the matches two per line.
P.S never store passwords in plaintext!
Upvotes: 1
Reputation: 3094
You can use the record separator flag -F
of awk
and separate at '
$> string="define('DB_USER', 'abc_12345');"
$> echo $string | awk -F"'" '{print $2}'
DB_USER
$> echo $string | awk -F"'" '{print $4}'
abc_12345
Or just simply pass the file
awk -F"'" '{print $2 $4}' file.txt
Upvotes: 3