Search code examples
shellgreppipels

Copying all the files modified this month from the command line


I want to copy all the files in a directory that were modified this month. I can list those files like this:

ls -l * | grep Jul 

And then to copy them I was trying to pipe the result into cp via xargs but had no success (I think) because I couldn't figure out how to parse the ls -l output to just grab the filename for cp.

I'm sure there are many ways of doing this; I'll give the correct answer out to the person who can show me how to parse ls -l in this manner (or talk me down from that position) though I'd be interested in seeing other methods as well.

Thanks!


Solution

  • Of course, just doing grep Jul is bad because you might have files with Jul in their name.

    Actually, find is probably the right tool for your job. Something like this:

    find $DIR -maxdepth 1 -type f -mtime -30 -exec cp {} $DEST/ \;
    

    where $DIR is the directory where your files are (e.g. '.') and $DEST is the target directory.

    • The -maxdepth 1 flag means it doesn't look inside sub-directories for files (isn't recursive)

    • The -type f flag means it looks only at regular files (e.g. not directories)

    • The -mtime -30 means it looks at files with modification time newer than 30 days (+30 would be older than 30 days)

    • the -exec flag means it executes the following command on each file, where {} is replaced with the file name and \; is the end of the command