I am trying to copy multiple files named "F3.bam" two level of directories to up and then rename these files with the name of the sub-directory after copy.
For example:
/samples/mydata1/RUN1/ID_date/PCR2/TIME1/F3.bam
/samples/mydata2/RUN1/ID2_date4/PCR2/TIME7/F3.bam
/samples/mydataxxx/RUN1/IDxxx_datexxx/PCR2/TIMExxx/F3.bam
Expected results:
1. The files are first copied two directories level up:
/samples/mydata1/RUN1/ID_date/F3.bam
/samples/mydata2/RUN1/ID2_date4/F3.bam
/samples/mydataxxx/RUN1/IDxxx_datexxx/F3.bam
2. The files are renamed according to the name of the current sub-directory:
/samples/mydata1/RUN1/ID_date/ID_date_F3.bam
/samples/mydata2/RUN1/ID2_date4/ID2_date4_F3.bam
/samples/mydataxxx/RUN1/IDxxx_datexxx/IDxxx_datexxx_F3.bam
Ideally a bash loop would be great (working on a Mac).
Best Answer
Here's the TLDR version of my solution: you can use the
dirname
andbasename
commands along with process substitution in order to construct the target path for your copy command.A longer explanation follows.
Here is a (super verbose) script that does roughly what you want using a Bash loop:
You can obviously compress this a lot, but I kept it this way for explanatory value.
Here is what the preceding script looks like without any comments or superfluous variables or
echo
statements:It's very fragile and doesn't do much in the way of error-handling. I also left in some
echo
statements for debugging so you see what it's doing and can sanity-check it when you run it for the first time.To test it I created your files by using the following script, which I include here in case you find it useful for further testing:
I check that the files were created properly by using the
find
command:Then I invoke the script like this:
And then I check that the script worked by using
find
again:Finally, I delete all of the test files, also using
find
: