How to move the files older than x days with similar directory structure?

Hello,

I need to move all the files inside /XYZ (has multi-depth sub directories) that are older than 14 days to /ABC directory but with retaining the SAME directory structure.

for example:
/XYZ/1/2/3/A/b.txt should be moved as /ABC/1/2/3/A/b.txt

I know about find /XYZ -type f -mtime +14 -exec mv {} /ABC \; but it would NOT retain the directory structure.

I thought of backing up whole /XYZ to /ABC and then delete recent 14 days' files from /ABC and all files older than 14 days from /XYZ but I find it very inefficient.

Appreciate any help. Thanks!

for file1 in `find /XYZ -type f -mtime +14`
do
  file2=${file1/XYZ/ABC} # You may use your own filters to formulate file2/dir2
  dir2=${file2%/*}
  mkdir -p $dir2
  cp $file1 $file2
done

Hmm. try this -

cd /XYZ
mkdir /ABC
find . -type f -mtime +14 |
while read fname 
do
   tar cf - $fname
done | (cd /ABC && tar xf -)
2 Likes

Thanks Jim.

It worked but I had to modify a bit like pushing done to the end.

The worked one:

cd /XYZ
mkdir -p /ABC
find . -type f -mtime +14 |
while read fname 
do
   tar cf - "${fname}" | (cd /ABC && tar xf -)
done

Thanks again Jim :slight_smile: