Accessing last x characters of a string in Bash

前端 未结 4 976
旧时难觅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:47

    1. Generalized Substring

    To generalise the question and the answer of gniourf_gniourf (as this is what I was searching for), if you want to cut a range of characters from, say, 7th from the end to 3rd from the end, you can use this syntax:

    ${string: -7:4}
    

    Where 4 is the length of course (7-3).

    2. Alternative using cut

    In addition, while the solution of gniourf_gniourf is obviously the best and neatest, I just wanted to add an alternative solution using cut:

    echo $string | cut -c $((${#string}-2))-
    

    Here, ${#string} is the length of the string, and the "-" means cut to the end.

    3. Alternative using awk

    This solution instead uses the substring function of awk to select a substring which has the syntax substr(string, start, length) going to the end if the length is omitted. length($string)-2) thus picks up the last three characters.

    echo $string | awk '{print substr($1,length($1)-2) }'
    

提交回复
热议问题