julesbou
julesbou

Reputation: 5780

Replace RegEx matches

I have a string like this : 'MDP_44' => 'sdDSD4343khjkjhkjhjk',

I want to run a function which return only: MDP_44.

I tried things like :

$ variable=     'MDP_44' => 'sdDSD4343khjkjhkjhjk',
$ echo ${var1//[^A-Z]}     // MDPDSD

But the result is not good.

Can someone help me to get MDP_44as the result ? Many thanks in advance.

Upvotes: 0

Views: 76

Answers (5)

glenn jackman
glenn jackman

Reputation: 247210

using bash regular expressions to find the text between the first set of single quotes.

if [[ "$variable" =~ [\']([^\']+) ]]; then match=${BASH_REMATCH[1]}; fi

Upvotes: 0

ghostdog74
ghostdog74

Reputation: 343141

Try removing all from => onwards

echo "${variable%%=>*}"

Upvotes: 0

Mu Qiao
Mu Qiao

Reputation: 7107

if your variable is:

variable="'MDP_44' => 'sdDSD4343khjkjhkjhjk',"

then you can use bash extended pattern matching:

echo ${variable//?(\'| =>*)}

Note you need to enable extglob by shopt -s extglob, it's enabled by default in interactive mode.

Upvotes: 1

Quamis
Quamis

Reputation: 11087

This will extract the first thing in '...'

echo "$variable" | cut -d\' -f2

Upvotes: 0

user647772
user647772

Reputation:

var="'MDP_44' => 'sdDSD4343khjkjhkjhjk',"
echo $var | cut -d= -f1 | sed "s/'//g"

EDIT

or even shorter

echo $var | cut -d\' -f2

Upvotes: 1

Related Questions