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

前端 未结 16 918
遥遥无期
遥遥无期 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:44

    If you like python and have an option to install a package, you can use this python utility.

    # install pythonp
    pythonp -m pip install pythonp
    
    echo "1:2:3:4:5" | pythonp "l.split(':')[-1]"
    5
    
    0 讨论(0)
  • 2020-11-27 09:45
    for x in `echo $str | tr ";" "\n"`; do echo $x; done
    
    0 讨论(0)
  • 2020-11-27 09:45

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

    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 讨论(0)
提交回复
热议问题