views:

64

answers:

5

hi,

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.

+1  A: 

Assuming fairly simple usage (no escaping of the delimiter, for example), you can use grep:

$ echo "1:2:3:4:5" | grep -oE "[^:]+$"
5

Breakdown - find all the characters not the delimiter ([^:]) at the end of the line ($). -o only prints the matching part.

Nicholas M T Elliott
+2  A: 

One way:

var1="1:2:3:4:5"
var2=${var1##*:}

Another, using an array:

var1="1:2:3:4:5"
saveIFS=$IFS
IFS=":"
var2=($var1)
IFS=$saveIFS
var2=${var2[@]: -1}

Yet another with an array:

var1="1:2:3:4:5"
saveIFS=$IFS
IFS=":"
var2=($var1)
IFS=$saveIFS
count=${#var2[@]}
var2=${var2[$count-1]}

Using Bash (version >= 3.2) regular expressions:

var1="1:2:3:4:5"
[[ $var1 =~ :([^:]*)$ ]]
var2=${BASH_REMATCH[1]}
Dennis Williamson
+5  A: 

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 ':'
 }
Stephen
A: 

using BAsh

$ var1="1:2:3:4:0"
$ IFS=":"
$ set -- $var1
$ eval echo  \$${#}
0
ghostdog74
+1  A: 

It's difficult to get the last field using cut, but here's (one set of) solutions in awk and perl

$ echo 1:2:3:4:5 | awk -F: '{print $NF'}
5
$ echo 1:2:3:4:5 | perl -F: -wane 'print $F[-1]'
5
William Pursell