3

I need to find all folders with the name "test" and move all folders along with the files inside up a level to their parent folders:

html/folder1/js/test -> html/folder1/test

html/folder2/js/test -> html/folder2/test

for over 500 folders

2

You can do this with a for loop in the directory that is the parent of folder1, folder2 etc (the html directory in your example) so first cd to it (replace with the real path:

cd /PATH/TO/html

In this command, if the name of what you want to move is not test then replace test with the real name or use * to move everything:

for dir in ./* ; do mv "$dir"/*/test "$dir"/ ; done

This will move all things named test (and all their contents, if they are directories) in sub-subdirectories of the current working directory to their parent directories but it will not delete the sub-subdirectories themselves (so js in your example, would not be deleted)

Example:

before:

.
├── 15
│   └── rainbow
│       ├── test
│       └── fun

after:

.
├── 15
│   ├── rainbow
│   └── test
│       └── fun

The command will throw an error for anything that is not a directory with this structure and matching contents, but it still does what you want, so please ignore this, or send the errors away by appending 2>/dev/null

for dir in ./* ; do mv "$dir"/*/test "$dir"/ ; done 2>/dev/null
2
  • Thank you for your help, but I need a bulk command to move more than 500 folders. – Paulo Rodrigues Jul 18 '16 at 16:42
  • @PauloRodrigues I've now changed my answer completely to do what you want – Zanna Jul 18 '16 at 21:39
2
find folder* -name 'test' -exec mv {} {}/../.. \;

Explanation

find folder* Searches in any ./folder* (glob patterns expanded by shell)

-name 'test' for files with name test.

-exec mv {} {}/../.. \; Moves them two levels higher1. {} is replaced with the found name. The -exec option must be terminated with an escaped semicolon. You can do a dry run by adding echo before mv.

1 Why two levels up? If we moved the folder into its parent folder, we’d ask to make it a subfolder of its current superfolder, so it will remain in the current place. However, we want to move it to become a subfolder of the parent’s parent. An expanded command will look like mv folder1/js/test folder1/js/test/../.. which is expanded to mv folder1/js/test folder1.

Note

Execution of this command will issue warnings like:

find: ‘folder1/js/test’: No such file or directory

because it’s trying to search in that folder after it has been moved. This can be silenced by specifying 2> /dev/null.

2
  • @Zanna Explanation added to the answer. What is happening in your case? – Melebius Jul 19 '16 at 6:59
  • Explanation clear. And it does work, if the target is a directory :) Nice! – Zanna Jul 19 '16 at 7:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.