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

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

提交回复
热议问题