I have a file.txt with a list of 100 files and their paths. Here are the first 3 entries:


I want to cp these files, rename the new files and put them in another dir & path, where the new dir name is the dir in the 8th level of the old path, and the new file name = new dir name + file extension. The new dir location also changes. I would get the new files sorted like this:

/project/msun/USERS/me/czi/data/map/MAP-9-003/MAP-9-003.bam #(old c44caf4c-cab7-4749-9940-a74a66bceec3.bam)
/project/msun/USERS/me/czi/data/map/MAP-9-007/MAP-9-007.bam #(old 3e5a10e0-3928-40c5-8dfb-9bbe9d5e0105.bam)
/project/msun/USERS/me/czi/data/map/MAP-9-013/MAP-9-013.bam #(old e230fce2-8f54-4d30-bb75-38d11a438f68.bam)

I found these posts: Using xargs to copy directories and Copy files with certain extension from many nested sub-directories to a single directory and append to each copied file the name of the directory

doing related tasks but I am unable to do my specific task

  • Welcome to the site. Please edit your post to indicate what you already tried, and where you faced specific problems. That way you can avoid receiving answers that you alread know won't work, or that rely on tools you don't have installed.
    – AdminBee
    Mar 2, 2023 at 8:42

1 Answer 1


I let you copy the files where you want. To rename, using Perl's rename:

Remove -n switch, aka dry-run when your attempts are satisfactory to rename for real.

mkdir -p ./project/msun/USERS/me/czi/data/map
rename -n 's@(project/msun/USERS/me/czi/data/)lb/(MAP-.*?)/.*/.*.bam@$1map/$2.bam@' ./project/msun/USERS/me/czi/data/lb/MAP-9-0*/*/*.bam
# rm -rf ./project/msun/USERS/me/czi/data/lb/MAP*
  • Thank you @Gilles Quénot ! Will the .bam files be renamed in the original folder or in the new folder? I'd like them to be renamed only in the new folder, please.
    – Lucas
    Mar 2, 2023 at 14:55
  • In the new one. The -n permit to test without doing for real as explained, to renane for real, remove -n switch. With -n you have just the output of what will be renamed in test mode. Mar 2, 2023 at 16:22
  • Thank you @Gilles. Apparently rename needs more arguments, with or without -n: rename: not enough arguments Try 'rename --help' for more information.
    – Lucas
    Mar 2, 2023 at 17:17
  • What is the output of rename --version ? Mar 2, 2023 at 22:18
  • it is: rename from util-linux 2.32.1
    – Lucas
    Mar 2, 2023 at 22:33

You must log in to answer this question.

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