Search code examples
bashgrepcut

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?


Solution

  • 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).