How to get the last character of a string in a shell?

前端 未结 10 2085
温柔的废话
温柔的废话 2020-12-22 18:54

I have written the following lines to get the last character of a string:

str=$1
i=$((${#str}-1))
echo ${str:$i:1}

It works for abcd/

相关标签:
10条回答
  • 2020-12-22 19:08

    Per @perreal, quoting variables is important, but because I read this post like 5 times before finding a simpler approach to the question at hand in the comments...

    str='abcd/'
    echo "${str: -1}"
    

    Output: /

    str='abcd*'
    echo "${str: -1}"
    

    Output: *

    Thanks to everyone who participated in this above; I've appropriately added +1's throughout the thread!

    0 讨论(0)
  • 2020-12-22 19:08
    echo $str | cut -c $((${#str}))
    

    is a good approach

    0 讨论(0)
  • 2020-12-22 19:09

    another solution using awk script:

    last 1 char:

    echo $str | awk '{print substr($0,length,1)}'
    

    last 5 chars:

    echo $str | awk '{print substr($0,length-5,5)}'
    
    0 讨论(0)
  • 2020-12-22 19:14

    For portability you can say "${s#"${s%?}"}":

    #!/bin/sh
    m=bzzzM n=bzzzN
    for s in \
        'vv'  'w'   ''    'uu  ' ' uu ' '  uu' / \
        'ab?' 'a?b' '?ab' 'ab??' 'a??b' '??ab' / \
        'cd#' 'c#d' '#cd' 'cd##' 'c##d' '##cd' / \
        'ef%' 'e%f' '%ef' 'ef%%' 'e%%f' '%%ef' / \
        'gh*' 'g*h' '*gh' 'gh**' 'g**h' '**gh' / \
        'ij"' 'i"j' '"ij' "ij'"  "i'j"  "'ij"  / \
        'kl{' 'k{l' '{kl' 'kl{}' 'k{}l' '{}kl' / \
        'mn$' 'm$n' '$mn' 'mn$$' 'm$$n' '$$mn' /
    do  case $s in
        (/) printf '\n' ;;
        (*) printf '.%s. ' "${s#"${s%?}"}" ;;
        esac
    done
    

    Output:

    .v. .w. .. . . . . .u. 
    .?. .b. .b. .?. .b. .b. 
    .#. .d. .d. .#. .d. .d. 
    .%. .f. .f. .%. .f. .f. 
    .*. .h. .h. .*. .h. .h. 
    .". .j. .j. .'. .j. .j. 
    .{. .l. .l. .}. .l. .l. 
    .$. .n. .n. .$. .n. .n. 
    
    0 讨论(0)
  • 2020-12-22 19:18

    That's one of the reasons why you need to quote your variables:

    echo "${str:$i:1}"
    

    Otherwise, bash expands the variable and in this case does globbing before printing out. It is also better to quote the parameter to the script (in case you have a matching filename):

    sh lash_ch.sh 'abcde*'
    

    Also see the order of expansions in the bash reference manual. Variables are expanded before the filename expansion.

    To get the last character you should just use -1 as the index since the negative indices count from the end of the string:

    echo "${str: -1}"
    

    The space after the colon (:) is REQUIRED.

    This approach will not work without the space.

    0 讨论(0)
  • 2020-12-22 19:18

    Single line:

    ${str:${#str}-1:1}
    

    Now:

    echo "${str:${#str}-1:1}"
    
    0 讨论(0)
提交回复
热议问题