Home > Blockchain >  Extract string in brackets using grep/sed/etc?
Extract string in brackets using grep/sed/etc?

Time:05-07

I am trying to obtain a file location for PHP-FPM, using the following piped commands works:

ps aux | grep php-fpm  | grep master

Results:

root        80  0.0  0.6 334912 26072 ?        Ss   14:18   0:00 php-fpm: master process (/root/.symfony/php/2b1b88a9c9ed1cd796c66569d386096e96bbe2bc/fpm-7.3.33.ini)

However I still need to extract the file path between the brackets, can't quite figure it out, the input string is complaining about illegal tokens..

RESULT_FROM_ABOVE | grep -o '^[\(^.\)]*'

bash: syntax error near unexpected token `('

This doesn't work but should give the gist of the idea of what I am trying to achieve.

I need to escape the RESULT_FROM_ABOVE before the final grep I am trying to apply and I can't find any solution.

Thoughts?

CodePudding user response:

Setup a couple variables to simulate the ps/grep/grep (pgg_out) and ps (ps_out) output:

$ pgg_out='root 80 0.0 0.6 334912 26072 ? Ss 14:18 0:00 php-fpm: master process (/root/.symfony/php/2b1b88a9c9ed1cd796c66569d386096e96bbe2bc/fpm-7.3.33.ini)'
$ ps_out='
some stuff to ignore
root 80 0.0 0.6 334912 26072 ? Ss 14:18 0:00 php-fpm: master process (/root/.symfony/php/2b1b88a9c9ed1cd796c66569d386096e96bbe2bc/fpm-7.3.33.ini)
more stuff to ignore'

Piping the current ps/grep/grep output to sed:

$ echo "${pgg_out}" | sed -En 's/.*\((.*)\)/\1/p'
/root/.symfony/php/2b1b88a9c9ed1cd796c66569d386096e96bbe2bc/fpm-7.3.33.ini

Eliminating OP's current grep calls and piping the ps output to awk:

$ echo "${ps_out}" | awk -F'[()]' '/master/ && /php-fpm/ {print $2}'
/root/.symfony/php/2b1b88a9c9ed1cd796c66569d386096e96bbe2bc/fpm-7.3.33.ini

CodePudding user response:

Using grep

$ grep -o '/[[:punct:][:alnum:]]*[^)]' file
/root/.symfony/php/2b1b88a9c9ed1cd796c66569d386096e96bbe2bc/fpm-7.3.33.ini
  • Related