I checked out the solution here, but it is not adressing my problem too well, because it does not use the specific structure of my naming.

I have a collection of files, enumerated and named in a systematic way, for instance


where x is a number that can be quite large and p is a marker for a "makrocollection". I would like to copy all files in such a makrocollection as a template and automatically rename all files copied as


With other words, is there an option that I can replace names automatically using the terminal (like it is possible in many editors) without working with additional documents?

Thank you in advance!

2 Answers 2


This could be a job for pax, assuming that there is a consistent naming convention.

cd directory

pax -rws/filep/fileq/ filep-* /path/to/copy/directory

Usually this can be done with a bash loop - not the quickest, but simple. In terminal type:

for f in filep-* ; do mv -iv "$f" "$(echo "$f" | sed 's/p/q/')" ; done


  • for f in filep-* ; do -> for all files called filep-anything, do the following
  • mv -iv A B move (=rename) A to B, while telling what you do -v and asking for confirmation before overwriting an existing file -i
  • were going to move a file "$f" (quotes for addressing problems with e.g. spaces in file names) to:
  • $( $echo $f | sed 's/A/B' ) print the file name then use sed to substitute the first(! and first only) occurence of A with B (this can also be sed 's/this123/that456/', but be aware that it will match the first hit)

For making sure it behaves as expected, run this first:

for f in filep-* ; do echo mv -iv "$f" "$(echo "$f" | sed 's/p/q/')" ; done

This will just print the command to be executed for each file and should look like mv -i filep-x fileq-x.

Note: this is for renaming the files and thus for after you copied them. This does not do the copying and renaming in one. Also it is meant to be executed form the directory where the files are.

  • I'm assuming you did not actually test your code, because the for ... in ... done commands, as written, couldn't possibly execute properly as you've referenced "$file" but not assigned it! It should be "$f" not "$file". Also, you're attempting to move a file that doesn't exist because for f in fileq-* is supposed to be for f in filep-*. The existing files have a p not q before the - in the OP and is supposed to be q as part of the rename. If I'm wrong about that, then your sed command would be wrong. Feb 23, 2017 at 1:43
  • @user3439894 - Thanks for the corrections. I DID test the code, yet used different variables, hence the mix-up between fileq- and filep- as well as between $file and $f (this one happens to me in half of my bash scripts... a bad habit). - Updated.
    – FelixJN
    Feb 23, 2017 at 7:37

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .