i have so many files under 300 different directories, file tree like:

 - ----abc
 - ----bcd
 - ----123
 - ----234

... etc.

I want to put them together under the same directory, like:

 - ----abc
 - ----bcd
 - ----123
 - ----234 ...

Is there any useful bash script in practical?

I coded this piece of bash script:

mkdir wavs

for ((i=1;i<=9;i++)); do
    cd ~/wav/train/S000$i
    mv * ~/wav/train/wavs
    cd .. done

for ((i=10;i<=99;i++)); do
    cd ~/wav/train/S00$i
    mv * ~/wav/train/wavs
    cd .. done

for ((i=100;i<=917;i++)); do
    cd ~/wav/train/S0$i
    mv * ~/wav/train/wavs
    cd .. done

echo "ok"

but i got the error which i dont understand:

./untar.sh: line 24: cd: /wav/train/S0917: No such file or directory 
cp: target '/wav/train/wavs/' is not a directory ok
  • Hello, David, I've wrote an answer which uses find, that IMO is the easiest way to do this job. If you need to create a bash script here is provided two variants that solve a similar task: askubuntu.com/a/1020671/566421 – pa4080 Apr 2 '18 at 9:57

Maybe the simplest way to do this job is by the command find (by default it works recursively):

find ~/wav/train/S* -type f -name "*.wav" -exec echo mv {} ~/wav/train/wavs/ \;
  • ~/wav/train/S* is the search path and it will match to each sub dir that starts with S.

  • -type f will limit the search only to the files.

  • -name "*.wav" will limit the search only to the files that ends with .wav. Not mandatory.

  • -exec ... \; will execute the mentioned command once for each search coincidence.

  • {} is a variable that contains the coincidence item.

  • remove echo from the command echo mv {} ~/wav/train/wavs/ to do the action.

Further if you want to delete the directories you can use a command as one of these:

find ~/wav/train/S* -type d -name "S*" -exec echo rm -r {} \;
find ~/wav/train/S* -type d -name "S*" -delete

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.