Accessing last x characters of a string in Bash

前端 未结 4 978
旧时难觅i
旧时难觅i 2020-12-07 09:36

I found out that with ${string:0:3} one can access the first 3 characters of a string. Is there a equivalently easy method to access the last three characters?

4条回答
  •  感动是毒
    2020-12-07 09:39

    You can use tail:

    $ foo="1234567890"
    $ echo -n $foo | tail -c 3
    890
    

    A somewhat roundabout way to get the last three characters would be to say:

    echo $foo | rev | cut -c1-3 | rev
    

提交回复
热议问题