0

I have a file name (including an extension, but not a full path name) in variable file, and I want to only get the last 10 characters of the base name from a parameter expansion.

Example: file contains the filename A_text_document_1234567890.txt.

Desired output: 1234567890.

I know that I can use ${file%.*} to remove the extension: echo ${file%.*} outputs A_text_document_1234567890.

If I do base=${file%.*}, then I can use ${base: -10} to get 1234567890.  Can I do this inside the parameter expansion all in one step without using a second variable?

I guess my real question is, how do I combine these two parameter expansions into one?

1 Answers1

3
file=abcdefghijklm
echo ${file: -10}
defghijklm

The space after the colon is required to differentiate that parameter expansion from the ${var:-default} variety.


Using a 2nd variable:

$ tmp=${file%.*}; echo "${tmp:(-10)}"
1234567890

Using a regular expression:

$ [[ $file =~ (.{10})(\.[^.]*)?$ ]] && echo "${BASH_REMATCH[1]}"
1234567890
glenn jackman
  • 85,964