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

前端 未结 16 917
遥遥无期
遥遥无期 2020-11-27 09:19

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

相关标签:
16条回答
  • 2020-11-27 09:24

    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]'
    
    0 讨论(0)
  • 2020-11-27 09:25

    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 ':'
     }
    
    0 讨论(0)
  • 2020-11-27 09:26

    Using Bash.

    $ var1="1:2:3:4:0"
    $ IFS=":"
    $ set -- $var1
    $ eval echo  \$${#}
    0
    
    0 讨论(0)
  • 2020-11-27 09:28

    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
    
    0 讨论(0)
  • 2020-11-27 09:29

    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.

    0 讨论(0)
  • 2020-11-27 09:30

    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.

    0 讨论(0)
提交回复
热议问题