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
    pic_1.png - p example makes no sense within the scope of the question – techraf Nov 22 '16 at 3:35
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.

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.