Denys
Denys

Reputation: 4557

Get the part of string after the delimiter

The string format is

Executed: variable_name

What is the simplest way to get the *variable_name* sub-string?

Upvotes: 1

Views: 187

Answers (4)

Jens
Jens

Reputation: 72639

foo="Executed: variable_name"
echo ${foo##* }     # Strip everything up to and including the rightmost space.

or

set -- $foo
echo $2

Unlike other solutions using awk, sed, and whatnot, these don't fork other programs and save thousands of CPU cycles since they execute completely in your shell. They are also more portable (unlike ${i/* /} which is a bashism).

Upvotes: 1

Dave
Dave

Reputation: 3623

If you have the string in a variable:

$ i="Executed: variable_name"
$ echo ${i/* /}
variable_name

If you have the string as output of a command

$ cmd
Executed: variable_name
$ cmd | awk '{print $NF}'
variable_name

Note that 'NF' means "number of fields", so $NF is always the last field on the line. Fields are assumed to be separated by spaces (unless -F is specified) If your variable_name could have spaces in it, the

-F' *: *'

mentioned previously ensures that only the ": " is used as a field separator. However, this will preserve spaces at the end of the line if there are any.

If the line is mixed in with other output, you might need to filter.

Either grep..

$ cmd | grep '^Executed: ' | awk '{print $NF}'

or more clever awk..

$ cmd | awk '/^Executed: /{print $NF}'

Upvotes: 0

anubhava
anubhava

Reputation: 785038

Using awk:

echo 'Executed: variable_name' | awk -F' *: *' '{print $2}'
variable_name

Upvotes: 0

pfnuesel
pfnuesel

Reputation: 15310

With :

echo "Executed: variable_name" | sed 's/[^:]*: //'

Upvotes: 0

Related Questions