Saeed
Saeed

Reputation: 4133

How to remove quotes with grep and cut in one command

This is what I do currently:

pass1=$(grep DB_PASSWORD /home/user/public_html/wp-config.php | cut -d ' ' -f3)
# it echoes 'password' with start and end single quotes
pass=${pass1:1:-1}
# it remove single quotes from start and end

But I want to combine these two commands in a single go.

I tried some wrong commands which showed me the help of grep.

Upvotes: 1

Views: 165

Answers (2)

The fourth bird
The fourth bird

Reputation: 163642

Using sed you can match the whole line and match the DB_PASSWORD field between the double quotes, and capture the inner text of the next field between double quotes in a capture group.

In the replacement use capture group 1.

pass=$(sed -En "s/^.*'DB_PASSWORD'[^']*'([^']+)'.*/\1/p" /home/user/public_html/wp-config.php)

Or ss your fields are separated by spaces, you could also get the 3rd field using awk, where \x27 matches a single quote which can be replaced by an empty string:

pass=$(awk '/DB_PASSWORD/{gsub("\x27", "", $3);print $3}' /home/user/public_html/wp-config.php)

Upvotes: 2

tink
tink

Reputation: 15248

You could use awk:

pass=$(awk -F"'" '/DB_PASSWORD/{print $4}' /home/user/public_html/wp-config.php)

I simply defined ' to be the field separator, which makes the password the 4th field.

Upvotes: 2

Related Questions