James Evans
James Evans

Reputation: 795

Get parts of string then update it

I have this string

blah --arg1 --arg2 --etc doh

sometimes doh ending in slash, sometimes not.

i need to extract doh and assign to a var.

then replace it with /some/path/doh

I wont put here my tries, they are way too ugly.

--- updated ---

mm, not sure i understand the answers, sorry.

the final string should be like:

blah --arg1 --arg2 --etc /some/path/doh

and doh assigned to a var, say foo

Upvotes: 2

Views: 98

Answers (4)

user904990
user904990

Reputation:

kinda ugly but working

first of all getting rid of eventual trailing slashes:

$ str='blah --arg1 --arg2 --etc doh///'
$ str=$(shopt -s extglob; echo "${str%%+(/)}")
$ echo $str
blah --arg1 --arg2 --etc doh

next extracting doh

$ var=${str##* }
$ echo $var
doh

and lastly removing it from string and adding back prefixed by /some/path

$ echo "${str%"$var"} /some/path/$var"
blah --arg1 --arg2 --etc  /some/path/doh

Upvotes: 1

Gilles Quénot
Gilles Quénot

Reputation: 185339

If it really arguments from script, see what's tripleee wrote.

If not:

echo "/some/path/$(echo "$STRING" | awk '{print $NF}')"

Upvotes: 0

Majid Laissi
Majid Laissi

Reputation: 19788

If the string is not command line arguments:

VAR="blah --arg1 --arg2 --etc doh"
LAST=`echo $VAR | awk -F" " '{ print $NF }'`
echo "/some/path/$LAST"

Upvotes: 0

tripleee
tripleee

Reputation: 189527

Assuming you use something like getopts to parse the options, it's just

echo "/some/path/$1"

Upvotes: 1

Related Questions