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?

user-2147482428
  • 33
  • 2
  • 10
  • 1
    You'd better show us the before and after: what is the filename, and what do you want to "pass it"? – glenn jackman Feb 26 '20 at 23:37
  • Does this answer your question? [Renaming a file in Bash using regular expressions](https://unix.stackexchange.com/questions/569389/renaming-a-file-in-bash-using-regular-expressions) – Jetchisel Feb 26 '20 at 23:49
  • That is `Parameter Expansion` the question is misleading... which has answered on some post here. – Jetchisel Feb 26 '20 at 23:49
  • You can't combine them. Take the result of one and apply the other expansion to that – muru Feb 27 '20 at 01:03
  • You can do that in standard shell, without using the non-POSIX `${var:off:len}` form, with `"${file#"${file%??????????}"}"` –  Feb 27 '20 at 11:22
  • @mosvy, that still doesn't help with removing the extension – ilkkachu Feb 27 '20 at 17:47
  • _"I guess my real question is, how do I combine these two parameter expansions into one?"_ -- You don't, not in Bash or ksh, but you can do it in Zsh. See the linked questions. – ilkkachu Feb 27 '20 at 17:49
  • @ilkkachu my comment should've probably went below the answer, since it was meant as a portable alternative to `${file: -10}`. –  Feb 27 '20 at 17:51
  • 1
    If the extension of the file is `.txt`, the solution in bash/ksh/zsh is obviously `"${file: -14:10}"` ;-) –  Feb 27 '20 at 18:02

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
  • 84,176
  • 15
  • 116
  • 168