4

I have a lot of csv files that I want to classify according to their filename in different folders.

  1. Files called *lefto.csv will be saved in a folder called lefto
  2. Files called *righto.csv will be saved in a folder called right
  3. Files called *sagital.csv will be saved in a folder called sagittal
  4. Files with names not obeying any previous condition, will be saved in a folder called animals

So far I have been using the mv command, but I would like to make a loop.

2 Answers 2

5

Seems like a case statement would be appropriate here. This should work in bash or other Bourne-like shells:

for f in *.csv; do 
  case "${f%.csv}" in 
    *.lefto) echo mv -- "$f" lefto/
    ;; 
    *.righto) echo mv -- "$f" righto/
    ;; 
    *.sagital) echo mv -- "$f" sagital/
    ;; 
    *) echo mv -- "$f" animals/
    ;; 
  esac
done

Testing:

touch foo.lefto.csv bar.righto.csv baz.csv foo.sagital.csv

then

mv -- bar.righto.csv righto/
mv -- baz.csv animals/
mv -- foo.lefto.csv lefto/
mv -- foo.sagital.csv sagital/

Remove the echos once you are convinced it is doing what you want

5

You could do something like this:

mkdir -p lefto righto sagital
for prefix in lefto righto sagital; do
    mv -- *"$prefix.csv" $prefix/
done 
mv -- *.csv animals/

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .