Jazz
Jazz

Reputation: 35

sed extract substring inclusive of pattern

I have below command to extract a substring from a string but it is excluding the patterns, can you please help.

echo ". ~/.bash_profile ; /home/script/sample.sh >> ~/log/sample.log" | sed -e 's/.*\/home\(.*\)sh.*/\1/'

Result: /script/sample

But I want the result to be /home/script/sample.sh

Upvotes: 0

Views: 170

Answers (2)

RavinderSingh13
RavinderSingh13

Reputation: 133518

In case your string /home/script/sample.sh coming always on same place then you could simply try:

echo ". ~/.bash_profile ; /home/script/sample.sh >> ~/log/sample.log" | cut -d' ' -f4
/home/script/sample.sh

In case you are ok with awk try following, irrespective of place of string home it will match regex and print it.

echo ". ~/.bash_profile ; /home/script/sample.sh >> ~/log/sample.log" | awk 'match($0,/\/home.*\.sh/){print substr($0,RSTART,RLENGTH)}'

Upvotes: 1

that other guy
that other guy

Reputation: 123470

The result is anything inside the capturing group \(..\), so just extend that around the whole piece you want:

echo ". ~/.bash_profile ; /home/script/sample.sh >> ~/log/sample.log" |
    sed -e 's/.*\(\/home.*sh\).*/\1/'

Upvotes: 3

Related Questions