Another Useful Copy Command

I last came up with this subject a while ago, whilst working on my own backup. Been needing something slightly different, which allows pulling out files of the same type. This one uses find rather than a straight cp function.

 find /pathtoinputdir/ -name “*.*” -type f -exec cp -urvp ‘{}’ /pathtooutputdir ;

I’ll break it down again:

 find /pathtoinputdir/ (pretty obvious, you could use just / to search your whole drive)

 -name “*.*”  (what to search for, replace *.* with anything you want to search for, but say you wanted to find all your jpg files, change it to *.jpg)

-type -f   (brings back files as opposed to directories)

-exec   (allows a function to run based upon what is found by find)

cp -urvp ‘{}’  (the copy with arguments and some magic (the brackets) which allows files and directories with spaces, newlines etc. See my other post to get descriptions of the cp arguments. You could replace cp with mv if you wanted to move and not copy)

/pathtooutputdir  (straight forward again, I create it first)

;    (more magic to go with the brackets)

Word of warning, if you have lots of files with the same name but different contents, you will overwrite the older ones with the latest one, regardless of content

2 thoughts on “Another Useful Copy Command

  1. @ Ozzyprv

    From the find man pages:

    -exec command {} +
    This variant of the -exec action runs the specified command on
    the selected files, but the command line is built by appending
    each selected file name at the end; the total number of invoca‐
    tions of the command will be much less than the number of
    matched files. The command line is built in much the same way
    that xargs builds its command lines. Only one instance of `{}’
    is allowed within the command. The command is executed in the
    starting directory.
    EXAMPLES
    find /tmp -name core -type f -print | xargs /bin/rm -f

    Find files named core in or below the directory /tmp and delete them.
    Note that this will work incorrectly if there are any filenames con‐
    taining newlines, single or double quotes, or spaces.

    find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f

    Find files named core in or below the directory /tmp and delete them,
    processing filenames in such a way that file or directory names con‐
    taining single or double quotes, spaces or newlines are correctly han‐
    dled. The -name test comes before the -type test in order to avoid
    having to call stat(2) on every file.

    find . -type f -exec file ‘{}’ ;

    Runs `file’ on every file in or below the current directory. Notice
    that the braces are enclosed in single quote marks to protect them from
    interpretation as shell script punctuation. The semicolon is similarly
    protected by the use of a backslash, though single quotes could have
    been used in that case also.

Leave a Reply

Your email address will not be published. Required fields are marked *