How to remove filename prefix with a Posix shell How to remove filename prefix with a Posix shell bash bash

How to remove filename prefix with a Posix shell


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


You have given very little information, but assuming you are doing this in bash, and have a list of files whose prefix needs to be removed, you can pipe the list through sed:

For example:

./generate_your_list_of_files | sed -e 's/^prefix//'

or if your list of files are space separated:

echo TD-file1 TD-file2.x.yt TD-file3-beep | sed -e 's/\<TD-//g'

The first one matches prefix in the beginning of the line and removes it. The second one matches TD- (or any other prefix you want to substitute) only when it happens at the beginning of a word and replaces it in all the matches in all the lines. This could get dangerous though, for example a file like TD-file\ that\ TD-contains\ space.txt becomes file\ that\ contains\ space.txt

As a side note, don't get your list of files using ls. That's a horrible mistake. If you need to get a list of files to work with and refer to in more than a single place, I'd suggest putting them in an array:

files=(*)

and then work with this array.


Due to popular requests (the single comment below), here is how to rename all files in the directory that start with XY TD- such that the prefix is removed (Thanks to @tripleee):

for file in prefix*;do    mv "$file" "${file#XY TD-}"done


You can also use the rename tool

Install it with homebrew

brew install rename

Then run the command below from within the directory to remove the "prefix-" from all files

rename -d prefix- *