user583507
user583507

Reputation:

Take token from this bash string/array...not sure which it is

Hi I am writing a bash script and I have a string

foo=1.0.3

What I want to do is examine the '3'. The first thing I did was get rid of the periods by doing this. bar=echo $foo|tr '.' ' ' with backticks around echo until the last single quote (not sure how to accomplish writing that.

When I do an echo $bar it prints 1 0 3. Now how do I create a variable that holds only the 3? thank you very much

Upvotes: 2

Views: 578

Answers (4)

Jed Daniels
Jed Daniels

Reputation: 25536

As you are no doubt learning about bash, there are many many ways to achieve your goals. I think @Mat's answer using bar=${foo##*.} is the best so far, although he doesn't explain how or why it works. I strongly recommend you check out the bash tutorial on tldp, it is my goto source when I have questions like this. For string manipulation, there is a section there that discusses many of the different ways to go about this sort of thing.

For example, if you know that foo is always going to be 5 characters long, you can simply take the fifth character from it:

bar=${foo:4}

That is, make bar the fifth position of foo (remember, we start counting from zero, not from one).

If you know it is always going to be the last position of foo, then you can just count backwards:

bar=${foo: -1}

Notice there is a space between the -1 and the colon, you need that (or parenthesis) to escape the negative sign.

To explain @Mat's answer, I had to look at the link I provided above. Apparently the double pound signs (hash mark, octothorpe, whatever you want to call them) in the expression:

${string##substring}

Mean to delete longest match of $substring from front of $string. So you are looking for the longest match of *. which equates to everything before a dot. Pretty cool, huh?

Upvotes: 2

Manny D
Manny D

Reputation: 20724

This should also work too:

echo $foo | awk -F. '{print $3}'

Upvotes: 0

Mat
Mat

Reputation: 206831

This should work:

bar=$(echo $foo|cut -d. -f3)

If you know you only want the part after the last dot (not the third item in a .-separated list) you can also do this:

bar=${foo##*.}

Advantage: no extra process or subshell started.

Upvotes: 1

Diego Sevilla
Diego Sevilla

Reputation: 29021

One way: Build an array and take position 2:

array=(`echo $foo | tr . ' '`)
echo ${array[2]}

Upvotes: 0

Related Questions