2

Say there are different files,

script.sh
text.txt
pic_1.png

or files with no extension - 'hello'. How can you extract the last character of base file name? ie,

script. sh - t
text.txt -  t
pic_1.png - p
hello - o

Is there like a simple way to do it?

1
  • 1
    pic_1.png - p example makes no sense within the scope of the question Commented Nov 22, 2016 at 3:35

2 Answers 2

3

First of all, you remove the extension if any:

name_no_ext=${file%.*}  

then, you get the last char:

char=${name_no_ext: -1} #note the space after colon  

If you want to learn more about string manipulation in bash, go to section Parameter Expansion of the bash manual.

0
2

POSIXLY:

for w in script.sh text.txt pic_1.png; do
  w=${w%.*}
  all_but_last_char=${w%?}
  w=${w##"$all_but_last_char"}
  printf '%s\n' "$w"
done

Note that it doesn't work with unicode characters in some shells like mksh, dash.

0

You must log in to answer this question.