How to get the last character of a string in a she

2020-02-16 06:01发布

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/:

$ bash last_ch.sh abcd/
/

It does not work for abcd*:

$ bash last_ch.sh abcd*
array.sh assign.sh date.sh dict.sh full_path.sh last_ch.sh

It lists the files in the current folder.

8条回答
萌系小妹纸
2楼-- · 2020-02-16 06:21

Single line:

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

Now:

echo "${str:${#str}-1:1}"
查看更多
Anthone
3楼-- · 2020-02-16 06:25

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)}'
查看更多
放我归山
4楼-- · 2020-02-16 06:28

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!

查看更多
我想做一个坏孩纸
5楼-- · 2020-02-16 06:30

I know this is a very old thread, but no one mentioned which to me is the cleanest answer:

echo -n $str | tail -c 1

Note the -n is just so the echo doesn't include a newline at the end.

查看更多
倾城 Initia
6楼-- · 2020-02-16 06:32

Every answer so far implies the word "shell" in the question equates to Bash.

This is how one could do that in a standard Bourne shell:

printf $str | tail -c 1
查看更多
成全新的幸福
7楼-- · 2020-02-16 06:33
echo $str | cut -c $((${#str}))

is a good approach

查看更多
登录 后发表回答