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

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

提交回复
热议问题