zeroweb
zeroweb

Reputation: 2752

How to extract a value within single quotes from a string?

I am trying to get the value from the string:

define('__mypassword', 'value');

I am trying to use cut and grep for this.

grep "__mypassword'" myfile.php | cut -d ',' -f 2

This returns 'value');

I do not need the quotes or braces or semi column. How do I take the value out without using multiple cut statements?

Upvotes: 1

Views: 507

Answers (3)

fedorqui
fedorqui

Reputation: 290515

Juse use awk!

$ awk -F"'" '/__mypassword/{print $4}' <<< "define('__mypassword', 'value');"
value

This sets the field separator to the single quote. This way, it is just a matter of printing the 4th element, which is the one after the 3rd quote. /__mypassword/ acts as grep "__mypassword".

In case you also need to match the single quote, use /__mypassword'\''/ (a bit picky, you need to close the awk statement to include a single quote).

Upvotes: 4

Kent
Kent

Reputation: 195289

kent$  grep -oP "[^']+(?='\))" <<<"define('__mypassword', 'value');"
value

Upvotes: 0

choroba
choroba

Reputation: 242423

Don't count commas, count single quotes:

grep "__mypassword'" myfile.php | cut -d"'" -f4

Upvotes: 3

Related Questions