Home > Back-end >  Move files from parent directories to subdirectories based on file extension
Move files from parent directories to subdirectories based on file extension

Time:11-18

I have 139 directories that contain a subdirectory and files that need to be moved into the subdirectory. I thought the simplest way to do this would be to use a mv command to recursively move the files based on their file extension of which there are only two. I have something like this:

xxx_03_001
 - xxx_03_001/xxx_03_001.csv
 - xxx_03_001/xxx_03_001.jpg
 - xxx_03_001/submissionDocumentation

xxx_03_002
 - xxx_03_002/xxx_03_002.csv
 - xxx_03_002/xxx_03_002.jpg
 - xxx_03_002/submissionDocumentation

I want:

xxx_03_001
 - xxx_03_001/submissionDocumentation/xxx_03_001.csv
 - xxx_03_001/submissionDocumentation/xxx_03_001.jpg

xxx_03_002
 - xxx_03_002/submissionDocumentation/xxx_03_002.csv
 - xxx_03_002/submissionDocumentation/xxx_03_002.jpg

How can I move these files recursively into the submissionDocumentation subdirectory within each parent directory?

CodePudding user response:

Run this in the top level directory:

for dir in xxx_*; do
    mv "$dir"/*.{csv,jpg} "$dir"/submissionDocumentation/
done

CodePudding user response:

On the top level:

find . -mindepth 1 -maxdepth 1 -type d | while read dir
 do
 [ -d "${dir}/submissionDocumentation/" ] && find ${dir} -mindepth 1 -maxdepth 1 -type f -exec mv {} ${dir}/submissinDocumentation/ \;
 done

CodePudding user response:

With Perl's standalone rename or prename command:

rename -n 's|(.*)/.*/(.*)|$1/submissionDocumentation/$2|' xxx_*/xxx_*/*

Output:

rename(xxx_03_001/xxx_03_001/xxx_03_001.csv, xxx_03_001/submissionDocumentation/xxx_03_001.csv)
rename(xxx_03_001/xxx_03_001/xxx_03_001.jpg, xxx_03_001/submissionDocumentation/xxx_03_001.jpg)
rename(xxx_03_002/xxx_03_002/xxx_03_002.csv, xxx_03_002/submissionDocumentation/xxx_03_002.csv)
rename(xxx_03_002/xxx_03_002/xxx_03_002.jpg, xxx_03_002/submissionDocumentation/xxx_03_002.jpg)

If everything looks fine, remove option -n.

  • Related