Find Command – How to Copy Files to Another Folder

findmkdir

I have to copy files to folder with name with their type using command 'find'. There are a lot of files with a lot of folders. I tried command:

find ./find -type f -exec bash -c ' file -b "$1"|cut -d " " -f 1 ' none {} \;

But I don't know how I can use mkdir to make folder, when I use "|".

I think about two command. First make the folders from type of files. Second copy files to this folder.

But how I can make this folders.

Best Answer

Using your file-cut expression to determine the directory name:

find . -type f -exec bash -c 'd="../$(file -b "$1"|cut -d " " -f 1)"; mkdir -p "$d"; cp "$1" "$d" ' none {} \;

How it works

  • d=../$(file -b "$1"|cut -d " " -f 1)

    This finds the name of the directory corresponding to the file's type. I added ../ so to put these under the parent directory. You may want to put them somewhere else.

  • mkdir -p "$d"

    This creates the directory if it doesn't already exist.

  • cp "$1" "$d"

    This copies the file to the directory.

Related Question