405

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.

17 Answers 17

600

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 ':'
 }
8
  • 8
    While this is working for the given problem, the answer of William below (stackoverflow.com/a/3163857/520162) also returns 5 if the string is 1:2:3:4:5: (while using the string operators yields an empty result). This is especially handy when parsing paths that could contain (or not) a finishing / character.
    – eckes
    Commented Jan 23, 2013 at 15:23
  • 12
    How would you then do the opposite of this? to echo out '1:2:3:4:'?
    – Dobz
    Commented Jun 25, 2014 at 11:44
  • 21
    And how does one keep the part before the last separator? Apparently by using ${foo%:*}. # - from beginning; % - from end. #, % - shortest match; ##, %% - longest match. Commented Jul 9, 2014 at 14:07
  • 2
    @Putnik that command sees pwd as a variable. Try dir=$(pwd); echo ${dir##*/}. Works for me!
    – Stan Strum
    Commented Dec 17, 2017 at 4:22
  • 2
    @Stan even shorter is echo ${$(pwd)##*/}
    – Cadoiz
    Commented Jun 15, 2021 at 22:37
417

Another way is to reverse before and after cut:

$ echo ab:cd:ef | rev | cut -d: -f1 | rev
ef

This makes it very easy to get the last but one field, or any range of fields numbered from the end.

11
  • 21
    This answer is nice because it uses 'cut', which the author is (presumably) already familiar. Plus, I like this answer because I am using 'cut' and had this exact question, hence finding this thread via search.
    – Dannid
    Commented Jan 14, 2013 at 20:50
  • 6
    Some cut-and-paste fodder for people using spaces as delimiters: echo "1 2 3 4" | rev | cut -d " " -f1 | rev
    – funroll
    Commented Aug 12, 2013 at 19:51
  • 2
    the rev | cut -d -f1 | rev is so clever! Thanks! Helped me a bunch (my use case was rev | -d ' ' -f 2- | rev Commented Sep 8, 2013 at 5:01
  • 1
    I always forget about rev, was just what I needed! cut -b20- | rev | cut -b10- | rev
    – shearn89
    Commented Aug 17, 2017 at 9:27
  • 1
    I ended up with this solution, my attempt o cut file paths with "awk -F "/" '{print $NF}' " broke somewhat for me, as file names including white spaces got also cut apart
    – THX
    Commented Feb 26, 2018 at 14:34
116

It's difficult to get the last field using cut, but here are some solutions in awk and perl

echo 1:2:3:4:5 | awk -F: '{print $NF}'
echo 1:2:3:4:5 | perl -F: -wane 'print $F[-1]'
4
  • 7
    great advantage of this solution over the accepted answer: it also matches paths that contain or do not contain a finishing / character: /a/b/c/d and /a/b/c/d/ yield the same result (d) when processing pwd | awk -F/ '{print $NF}'. The accepted answer results in an empty result in the case of /a/b/c/d/
    – eckes
    Commented Jan 23, 2013 at 15:20
  • @eckes In case of AWK solution, on GNU bash, version 4.3.48(1)-release that's not true, as it matters whenever you have trailing slash or not. Simply put AWK will use / as delimiter, and if your path is /my/path/dir/ it will use value after last delimiter, which is simply an empty string. So it's best to avoid trailing slash if you need to do such a thing like I do.
    – stamster
    Commented May 21, 2018 at 11:52
  • How would I get the substring UNTIL the last field?
    – blackjacx
    Commented Jun 9, 2020 at 16:28
  • 1
    @blackjacx There are some quirks, but something like awk '{$NF=""; print $0}' FS=: OFS=: often works well enough. Commented Jun 9, 2020 at 16:50
41

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.

1
  • 1
    -E means using extended syntax; [^...] means anything but the listed char(s); + one or more such hits (will take the maximum possible length for the pattern; this item is a gnu extension) - for the example the separating char(s) are the colon. Commented Oct 17, 2019 at 11:36
29

You could try something like this if you want to use cut:

echo "1:2:3:4:5" | cut -d ":" -f5

You can also use grep try like this :

echo " 1:2:3:4:5" | grep -o '[^:]*$'
1
  • 1
    Your second command was useful to me. Would you break it down so I can understand it better? Thank you.
    – John
    Commented Mar 2, 2021 at 15:09
20

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]}
0
18
$ echo "a b c d e" | tr ' ' '\n' | tail -1
e

Simply translate the delimiter into a newline and choose the last entry with tail -1.

1
  • 3
    It will fail if the last item contains a \n, but for most cases is the most readable solution.
    – Yajo
    Commented Jul 30, 2014 at 10:13
7

Using sed:

$ echo '1:2:3:4:5' | sed 's/.*://' # => 5

$ echo '' | sed 's/.*://' # => (empty)

$ echo ':' | sed 's/.*://' # => (empty)
$ echo ':b' | sed 's/.*://' # => b
$ echo '::c' | sed 's/.*://' # => c

$ echo 'a' | sed 's/.*://' # => a
$ echo 'a:' | sed 's/.*://' # => (empty)
$ echo 'a:b' | sed 's/.*://' # => b
$ echo 'a::c' | sed 's/.*://' # => c
1
  • given the output of many utilities is in the form of the original file name followed by colon (:) followed by the utility's output (${path}:${output}), this is incredibly useful for adding your own control character like TAB $'\t' or unit separator $'\037' etc. after that final colon. example for adding a TAB at the final colon of file output: file ~/yourPath/* | sed "s/\(.*:\)\(.*\)/\1"$'\t'"\2/"
    – spioter
    Commented Sep 3, 2020 at 13:48
5

There are many good answers here, but still I want to share this one using basename :

 basename $(echo "a:b:c:d:e" | tr ':' '/')

However it will fail if there are already some '/' in your string. If slash / is your delimiter then you just have to (and should) use basename.

It's not the best answer but it just shows how you can be creative using bash commands.

4

If your last field is a single character, you could do this:

a="1:2:3:4:5"

echo ${a: -1}
echo ${a:(-1)}

Check string manipulation in bash.

2
  • 1
    This doesn't work: it gives the last character of a, not the last field. Commented Nov 13, 2013 at 16:15
  • 1
    True, that's the idea, if you know the length of the last field it's good. If not you have to use something else...
    – Ab Irato
    Commented Nov 25, 2013 at 13:25
2

Using Bash.

$ var1="1:2:3:4:0"
$ IFS=":"
$ set -- $var1
$ eval echo  \$${#}
0
1
  • 1
    Could have used echo ${!#} instead of eval echo \$${#}. Commented Apr 27, 2017 at 22:10
2

Regex matching in sed is greedy (always goes to the last occurrence), which you can use to your advantage here:

$ foo=1:2:3:4:5
$ echo ${foo} | sed "s/.*://"
5
1
echo "a:b:c:d:e"|xargs -d : -n1|tail -1

First use xargs split it using ":",-n1 means every line only have one part.Then,pring the last part.

0
1

A solution using the read builtin:

IFS=':' read -a fields <<< "1:2:3:4:5"
echo "${fields[4]}"

Or, to make it more generic:

echo "${fields[-1]}" # prints the last item
0
for x in `echo $str | tr ";" "\n"`; do echo $x; done
1
  • 2
    This runs into problems if there is whitespace in any of the fields. Also, it does not directly address the question of retrieving the last field.
    – chepner
    Commented Jun 22, 2012 at 12:58
0

improving from @mateusz-piotrowski and @user3133260 answer,

echo "a:b:c:d::e:: ::" | tr ':' ' ' |  xargs | tr ' ' '\n' | tail -1

first, tr ':' ' ' -> replace ':' with whitespace

then, trim with xargs

after that, tr ' ' '\n' -> replace remained whitespace to newline

lastly, tail -1 -> get the last string

6
  • 1
    If you want to contribute an answer according to How to Answer please edit to make that more obvious. You can provide an answer based on an existing answer; giving credit to the exsting answers author is then very appropriate, thanks for doing that. I do however have trouble identifying the answer you are reffering to. Please use the link you get from the "Share" link beneath that answer to add an unambigous link here.
    – Yunnosch
    Commented Nov 19, 2022 at 6:25
  • 1
    You know about the commenting privilege which you do not have, so well that you can even put it into words. You are aware of the rule meta.stackexchange.com/questions/214173/… . In that situation please do not decide to misuse a different mechanism (an answer) for something it is not meant for and which you are not allowed yet to do.
    – Yunnosch
    Commented Nov 19, 2022 at 6:25
  • As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
    – Community Bot
    Commented Nov 22, 2022 at 12:09
  • Thanks for the reminder @Yunnosch, as i am not a native english speaker, i may make mistakes, for all this time using SO just seeking/reading for answers of questions and not answering questions. Commented Feb 13, 2023 at 16:15
  • You only describe the code behaviour on a level which (with some experiece) is clear by the code itself. Please explain what it avhieves, i.e. wha the improvement is.
    – Yunnosch
    Commented Feb 13, 2023 at 16:21
-2

For those that comfortable with Python, https://github.com/Russell91/pythonpy is a nice choice to solve this problem.

$ echo "a:b:c:d:e" | py -x 'x.split(":")[-1]'

From the pythonpy help: -x treat each row of stdin as x.

With that tool, it is easy to write python code that gets applied to the input.

Edit (Dec 2020): Pythonpy is no longer online. Here is an alternative:

$ echo "a:b:c:d:e" | python -c 'import sys; sys.stdout.write(sys.stdin.read().split(":")[-1])'

it contains more boilerplate code (i.e. sys.stdout.read/write) but requires only std libraries from python.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.