Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string in shell and get the last field

Suppose I have the string 1:2:3:4:5 and I want to get its last field (5 in this case). How do I do that using Bash? I tried cut, but I don't know how to specify the last field with -f.

like image 512
cd1 Avatar asked Jul 01 '10 23:07

cd1


People also ask

How do you get the last character of a string in shell?

To access the last character of a string, we can use the parameter expansion syntax ${string: -1} in the Bash shell. In bash the negative indices count from the end of a string, so -1 is the index of a last character.

How do I split a string on a delimiter in bash?

In bash, a string can also be divided without using $IFS variable. The 'readarray' command with -d option is used to split the string data. The -d option is applied to define the separator character in the command like $IFS. Moreover, the bash loop is used to print the string in split form.

How do I get the last 4 characters of a string in bash?

To access the last n characters of a string, we can use the parameter expansion syntax ${string: -n} in the Bash shell. -n is the number of characters we need to extract from the end of a string.


1 Answers

You can use string operators:

$ foo=1:2:3:4:5 $ echo ${foo##*:} 5 

This trims everything from the front until a ':', greedily.

${foo  <-- from variable foo   ##   <-- greedy front trim   *    <-- matches anything   :    <-- until the last ':'  } 
like image 124
Stephen Avatar answered Sep 30 '22 07:09

Stephen