Ubuntu – Script for β€œextracting” subfolders into parent folder

bashdirectorymvscripts

This gonna be a little bit tricky, I guess πŸ™‚

When I open a terminal in the folder and run a script, that script should:

  1. move all content of all subfolders to a top parent folder (recursively)
  2. delete all empty folders

Parent folder we are standing in will contain no folders, just content of all of them.

It should work for hidden files and folders as well. It would be immensely useful for house cleaning πŸ™‚

I've tried something like:

find . -type f -name "*" -depth | xargs mv ./

But with no luck.

Thank you for your help πŸ™‚

Best Answer

The simplest and cleanest way in my opinion would be to use this command:

find . -type f -exec mv --backup=numbered {} . \; && find . -maxdepth 1 -type d -exec rm -r {} +

find command #1:

  • .: searches in the current working directory;
  • -type f: searches for files;
  • -exec [...]: executes either a command for each result (using {} [...] \;) or a command for all the results (using {} +);
  • mv --backup=numbered . \;: moves each result in the current working directory, creating a backup of files with the same filename already in the current working directory;

find command #2:

  • .: searches in the current working directory;
  • -maxdepth 1: searches only in the first level of the target directory hierarchy;
  • -type d: searches for directories;
  • -exec [...]: executes either a command for each result (using {} [...] \;) or a command for all the results (using {} +);
  • rm -r {} +: deletes each result;

Test on a test directory hierarchy:

user@debian ~/tmp % tree -a
.
β”œβ”€β”€ 1
β”‚Β Β  β”œβ”€β”€ file1
β”‚Β Β  β”œβ”€β”€ file2
β”‚Β Β  β”œβ”€β”€ file3
β”‚Β Β  └── .hidden
β”œβ”€β”€ 2
β”‚Β Β  β”œβ”€β”€ file1
β”‚Β Β  β”œβ”€β”€ file2
β”‚Β Β  β”œβ”€β”€ file3
β”‚Β Β  └── .hidden
└── 3
    β”œβ”€β”€ file1
    β”œβ”€β”€ file2
    β”œβ”€β”€ file3
    └── .hidden

3 directories, 12 files
user@debian ~/tmp % find . -type f -exec mv --backup=numbered {} . \; && find . -type d -exec rm -r {} +
rm: refusing to remove "." or ".." directory: skipping "."
user@debian ~/tmp % tree -a
.
β”œβ”€β”€ file1
β”œβ”€β”€ file1.~1~
β”œβ”€β”€ file1.~2~
β”œβ”€β”€ file2
β”œβ”€β”€ file2.~1~
β”œβ”€β”€ file2.~2~
β”œβ”€β”€ file3
β”œβ”€β”€ file3.~1~
β”œβ”€β”€ file3.~2~
β”œβ”€β”€ .hidden
β”œβ”€β”€ .hidden.~1~
└── .hidden.~2~

0 directories, 12 files