Ubuntu: Organising folders


I have several folders ("amazon", "niger", "rhine",...). Inside each of them I have several subfolders ("gfdl", "hadgem", "ipsl",...). Each subfolders is composed by 5 subfolders (e.g. in "amazon", the subfolder "gfdl" is composed by 5 subfolder 'amazon_gfdl', 'amazon_gfdl1', ..., 'amazon_gfdl5'); and the others subfolders follow the same structure (e.g. in "amazon" subfolder "ipsl" is composed by 5 subfolders 'amazon_ipsl', 'amazon_ipsl1', 'amazon_ipsl2',...until 'amazon_ipsl5'.

I have a huge amount of folder following the same frame of organisation. Therefore my question is the following:

How can I organise each folder and subfolder in such a way that in each subfolder ("gfdl", "hadgem","ipsl",...), 4 new directories are created ("1", "2", "3", "4"); and then that the folder e.g. "amazon_gfdl" (already present in "gfdl") is copied in each of those new directories and finally that "amazon_gfdl1" is moved to the new directory "1", "amazon_gfdl2" is moved to the new directory "2", and so on!

I am currently using the command cp and move within each subfolders but it´s not really efficient and I might need an extra life to end this task like that! Therefor any helps or hint will be greatly appreciated. Thanks you very much!


You can run this script, it does nothing but echo the commands. When it does what you want, replace the dont=echo by dont= ie nothing.

dont=echo  for dir in */*  do if ! [[ "$dir" =~ [1234]$ ]]     then file=${dir/\//_}          for i in 1 2 3 4          do $dont mkdir $dir/$i             $dont cp -r $dir/$file $dir/$i             $dont mv $dir$i $dir/$i          done     fi  done  


You should try writing something similar to this:

for dir in */; do    echo "Moving into $dir"    cd "$dir"    for subDir in */; do      echo "Moving into $subDir"      cd "$subDir"      for num in 1 2 3 4; do        echo "Moving $dir_$sudDir$num to $num"        mv -vRi "$dir_$sudDir$num" "$num"      done    done  done  

I have not tested this, and don't recommend running it until you have tested it. Some mv flags won't work on Mac OSX because of the version of bash it runs - but it should work on Ubuntu.

Again - mess around with the above code until it does what you want - you might want to look into bash for loops in general, or possibly using a find command to execute a similar block of code in one line.

Related: How do I rename a directory via the command line?

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »