Copy latest modified file from all subdirectories to a new directory having same sub directory structure

1k Views Asked by At

I have a directory having 100 sub directories each one having 100 files. Every day number of files in each sub directory increases by one. I want to write a script in Linux to copy all 100 sub directories in another location each having only one latest file. How this can be done?

2

There are 2 best solutions below

0
On BEST ANSWER

You can modify if block as:

if [ $f != "./directory_to_cop" ]
    then
              mkdir ./directory_to_copy/$f 2>/dev/null
              cp $f/`ls -t $f | head -1` ./directory_to_copy/$f
    fi

and if out directory is not inside current directory:

mkdir path_to_directory/name_of_directory/$f 2>/dev/null

cp $f/`ls -t | head -1` path_to_directory/name_of_directory/$f
2
On

From your current directory (which is having 100 sub directories) you can run script as:

   for f in `find ./* -maxdepth 0 -type d`
do
        if [ $f != "./directory_to_copy" ]
        then
                  cp $f/`ls -t $f | head -1` ./directory_to_copy
        fi
 done

And if your out directory is not in current directory you can skip the If statement and you can specify relative path or absolute path to the directory where you need to store with name in cp statement as:

cp $f/`ls -t $f | head -1` path_to_directory/name_of_directory