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

前端 未结 16 919
遥遥无期
遥遥无期 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:30
    $ 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.

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

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

    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.

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

    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.

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

    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.

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