How to remove filename prefix with a Posix shell

hamid picture hamid · May 10, 2012 · Viewed 34.5k times · Source

How can I remove the filename prefix in Bash as in the following example:

XY TD-11212239.pdf

to get

11212239.pdf

i.e, remove XY TD-?

Answer

David W. picture David W. · Aug 27, 2014

You said POSIX shells which would include BASH, Kornshell, Ash, Zsh, and Dash. Fortunately, all of these shells do pattern filtering on variable values.

Patterns are what you use when you specify files with things like * on the Unix/Linux command line:

$ ls *.sh  # Lists all files with a `.sh` suffix

These POSIX shells use four different pattern filtering:

  • ${var#pattern} - Removes smallest string from the left side that matches the pattern.
  • ${var##pattern} - Removes the largest string from the left side that matches the pattern.
  • ${var%pattern} - Removes the smallest string from the right side that matches the pattern.
  • ${var%%pattern} - Removes the largest string from the right side that matches the pattern.

Here are a few examples:

foo="foo-bar-foobar"
echo ${foo#*-}   # echoes 'bar-foobar'  (Removes 'foo-' because that matches '*-')
echo ${foo##*-}  # echoes 'foobar' (Removes 'foo-bar-')
echo ${foo%-*}   # echoes 'foo-bar'
echo ${foo%%-*}  # echoes 'foo'

You didn't really explain what you want, and you didn't include any code example, so it's hard to come up with something that will do what you want. However, using pattern filtering, you can probably figure out exactly what you want to do with your file names.

file_name="XY TD-11212239.pdf"
mv "$file_name" "${file_name#*-}" # Removes everything from up to the first dash