Thursday, October 28, 2021

[SOLVED] Extracting group from regex in shell script using grep

Issue

I want to extract the output of a command run through shell script in a variable but I am not able to do it. I am using grep command for the same. Please help me in getting the desired output in a variable.

x=$(pwd)
pw=$(grep '\(.*\)/bin' $x)
echo "extracted is:"
echo $pw

The output of the pwd command is /opt/abc/bin/ and I want only /root/abc part of it. Thanks in advance.


Solution

Use dirname to get the path and not the last segment of the path.



Answered By - sashang