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?

techraf
  • 5,831
  • 10
  • 33
  • 51
Rinato Fenice
  • 21
  • 1
  • 3

2 Answers2

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.

SparedWhisle
  • 3,588
  • 4
  • 22
  • 35
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.

cuonglm
  • 150,973
  • 38
  • 327
  • 406