Shell script to move all files from subfolders to parent folder

I've bunch of folders in folder A. I want to move files from all those folders to A.

Or

I want to cut all files from child folders and paste them in parent folder.

How to do that?


Solution 1:

Go to your A directory and run

find . -mindepth 2 -type f -print -exec mv {} . \;

which means "find all files in this directory and its sub-directories and execute mv with target directory . for each file found to move them to current directory.

Solution 2:

Well you could create a file and name it "cutme" (to create a file called cutme in the terminal type nano cutme. To save it press CTRL+X then press ENTER.) for example and paste the following in it assuming that:

  1. You want to do this recursively (In subfolders and subfolders of those subfolders)
  2. You want to skip moving the script file
  3. You have permissions to move the files in that folder
  4. Files may or may not include spaces in their names

find * -type f -print -not -type d -and -not -regex 'cutme' -exec mv {} .. \;

Note the name cutme inside the line. It should be the same as the script you will run.

After creating the file and pasting the above line, run the following in the same folder as the script:

chmod +x cutme. This will give your new file the "Executable" flag so you can execute it like this: ./cutme.