1

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

--s1
 - ----abc
 - ----bcd
--s2
 - ----123
 - ----234

... etc.

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

--whole
 - ----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
muru
  • 197,895
  • 55
  • 485
  • 740
  • 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: https://askubuntu.com/a/1020671/566421 – pa4080 Apr 02 '18 at 09:57

1 Answers1

1

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
pa4080
  • 29,831