Pravin
Pravin

Reputation: 13

Extract shortest suffix following a certain character

I have a string as below which gets added from right side and need to fetch the last words every time I ran in my script automatically.

string='apple:v1 banana:v3 pineapple:v3'

Now I want output as v3 in this case but I have this string not static it gets always added from right side like:

string='apple:v1 banana:v3 pineapple:v3 mango:v4 strawberry:v5'

Here the output ought to be v5.

Now we have cut command in shell where we can fetch as

myoutput="(echo "$string" | cut -d ':' -f5)

to v5 do we have any command or argument more where i can use to get the latest added vx details whenever my string gets added with new output.

Upvotes: 1

Views: 73

Answers (4)

stack0114106
stack0114106

Reputation: 8711

You can try Perl

$ echo "apple:v1 banana:v3 pineapple:v3" | perl -ne ' /.*:(.+)/omg and print $1 '
v3
$ echo 'apple:v1 banana:v3 pineapple:v3 mango:v4 strawberry:v5' | perl -ne ' /.*:(.+)/omg and print $1 '
v5
$

Upvotes: 0

Pravin
Pravin

Reputation: 13

To get the last field, we can reverse the string and pluck out the first field; in my case

myoutput="$(echo "$string" | rev | cut -d ':' -f1 | rev)"

echo "$myoutput" will print the extracted field.

Upvotes: 0

Raman Sailopal
Raman Sailopal

Reputation: 12887

Awk is an alternate option:

awk -F: '{ print $NF }' <<< "$string"

Set the delimiter to : and then print the last field ($NF)

Upvotes: 0

oguz ismail
oguz ismail

Reputation: 50785

You don't need an external utility for that.

$ string='apple:v1 banana:v3 pineapple:v3'
$ echo "${string##*:}"
v3
$
$ string='apple:v1 banana:v3 pineapple:v3 mango:v4 strawberry:v5'
$ echo "${string##*:}"
v5

See Shell Parameter Expansion.

Upvotes: 5

Related Questions