Chanchal singh
Chanchal singh

Reputation: 135

Regex for pattern matching in shell script and extract the match part

Hope you are doing.

I need help in regex in the shell script.

the input is:

PM_path='SubNetwork=IMS,SubNetwork=IMS,MeContext=R9NEXRERNFVCSS01_PS'**PM_path='SubNetwork=IMS,SubNetwork=IMS,MeContext=R9NEXRERNFVCSS01_PS'

the output I want as:

R9NEXRERNFVCSS01_PS that is everything after the last equal sign.

Right now I have implemented it as below:

if [[ $PM_path =~ MeContext=([a-zA-Z0-9_]+) ]]; then  
      NODE_NAME=${BASH_REMATCH[1]}
 echo "the value is matched";

So here I have put a check at MeContext and this is a part of PM_path.

I wanted to make it more generic like select everything which appears after the last equal sign.

Please help.

Thanks in advance.

Upvotes: 6

Views: 2503

Answers (3)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626794

You can simply get the value using Bash string manipulation:

PM_path="${PM_path##*=}"

Here, ${PM_path##*=} means that you want to remove as many chars as possible from the left (##*) till the last = char.

See the 10.1. Manipulating Strings reference:

${string##substring}
Deletes longest match of $substring from front of $string.

See an online demo:

PM_path='SubNetwork=IMS,SubNetwork=IMS,MeContext=R9NEXRERNFVCSS01_PS'
PM_path="${PM_path##*=}"
echo "$PM_path"
# => R9NEXRERNFVCSS01_PS

ANSWER TO YOUR COMMENT:

You mention you have a trailing / char at the end of your string. You can still use the same technique, remove / from the result obtained with the preceding step:

PM_Path="SubNetwork=IMS,SubNetwork=IMS,MeContext=R9NEXRERNFVCSS01_PS/"
PM_Path="${PM_Path##*=}"
PM_Path="${PM_Path/\//}"
echo "$PM_Path"

See the online demo, PM_Path="${PM_Path/\//}" removes the first / in the string.

Upvotes: 2

anubhava
anubhava

Reputation: 785108

I wanted to make it more generic like select everything which appears after the last equal sign.

You may use:

[[ $PM_path =~ .*=([^/]+) ]] && echo "${BASH_REMATCH[1]}"
R9NEXRERNFVCSS01_PS

.* matches longest possible text from start then we match a =. Finally we match and capture remaining string of 1+ non-/ characters in ([^/]+) that we print using echo "${BASH_REMATCH[1]}"

Upvotes: 4

RavinderSingh13
RavinderSingh13

Reputation: 133478

You could use grep here, with GNU grep please try following. Simply using grep's -o and -P option(to enable PCRE regex). Then in regex matching everything till last occurrence of = and using \K to discard matched part and .* followed by it will print the rest of the value from variable.

echo "$PM_path" | grep -oP '.*=\K.*'

Upvotes: 6

Related Questions