Reputation: 2528
Okay the answer to this may be really simple but I have been searching for a while and I can't figure it out. I have a variable called "tmessagef". The variable is formatted like:
value1*value2*vlaue3*value4*value5
The only part of the variable I want is value 5. I am currently using the following code but it only prints each value and doesn't save them to a variable:
OIFS=$IFS
IFS='*'
arr2=$tmessagef
for x in $arr2
do
echo "$x"
done
IFS=$OIFS
What I want to do is get the 5th line that the echo command produces and save that to a variable called "tmessage". How would I go about doing this?
Thanks in advance.
Upvotes: 0
Views: 2812
Reputation: 360
Can you use cut?
VAL=`echo 'value1*value2*vlaue3*value4*value5' | cut -f5 -d'*'`
Upvotes: 0
Reputation: 6207
I believe mcalex's comment should answer it:
Change
echo "$x"
totmessage="$x"
. At the end of the loop $val will contain the last value
Upvotes: 0
Reputation: 8398
For this very specific scenario (where you only want to extract the value at the very end), you can use parameter expansion
echo "${word##*\*}"
or assign it to a variable instead of using "echo".
Explanation:
##
removes the longest substring anchored at the beginning that matches the pattern*
matches any number of any character\*
matches a literal asterisk So basically, remove the longest substring that ends with an asterisk.
Upvotes: 1
Reputation: 6577
IFS=* read -r _{,,,} tmessage _ <<<"$tmessagef"
or
[[ $tmessagef =~ ^(.*\*){4}(.*)\* ]]; tmessage=${BASH_REMATCH[2]}
Read http://mywiki.wooledge.org/BashFAQ/001 and the trillion other answers to this question.
Don't use echo for this. If you have output that needs saving, see: http://mywiki.wooledge.org/BashFAQ/002
Upvotes: 0
Reputation: 179392
Array manipulation:
OIFS="$IFS" IFS='*' Y=($X)
x=${Y[${#Y[@]}-1]}
IFS="$OIFS"
Upvotes: 1