Reputation: 29427
I have to copy many files from different folders.
Example of the source Folder structure
Source folder has the following structure
root
- folder1
- folder1.txt
- folder2
- folder2.csv
- folder3
- folder3.txt
Example of the destination Folder structure
Destination folder should be like this following structure
root
- folder1
- folder1.txt
- folder3
- folder3.txt
To accomplish the generic copy and recreating the folder structure I have used the following script:
cp src/**/*.txt dest/
for file in $(ls *.txt);
do mkdir -p source/${file%.*}/ && mv $file dest/${file%.*}/;
done
First of all I copy all the file in the destination folder. Based on the assumption that every file is inside a folder which has the same name then I am moving the files recreating the original structure. This script effectively works very well.
Now the requirement has changed to support multiple level folder structure. E.g.
root
- folder1
- folder11
- folder11.txt
- folder2
- folder2.csv
- folder3
- folder3.txt
How can I adapt the script to remain generic?
Upvotes: 0
Views: 112
Reputation: 1819
This might work for you:
#!/usr/bin/env bash
shopt -s globstar
src=some/src/path
dest=some/dest/path
for f in "$src"/**/*.txt; do
d=${f#"$src"} d=$dest/${d%/*}
mkdir -p -- "$d" || continue
cp -- "$f" "$d"
done
Upvotes: 2