Home > Enterprise >  Sort files into different folders based on their beginning
Sort files into different folders based on their beginning

Time:06-24

I'm creating a script in BASH that will sort my files into different folders based on the beginning of the name. For example, the files are called A1_a.txt, A1_aa.txt, A1_aaa.txt, A2_aa.txt, A2_aa.txt, A2_aaa.txt. and based on whether they are A1 or A2 wants to move them to new1 for A1, and new2 for A2. I have to use a for loop for this task

I created such a script but it gets an error.

for i in $(ls | grep "A1"|"A2"); do if [ ${i} = "A1" ] then mv ${i} new1 else mv ${i} new2 fi; done

error: -bash: syntax error near unexpected token `done'

I don't understand why he got such an error, badly created if in for loop?

After adding semicolons; enter image description here

After adding semicolons and removing "" in grep, also switching all ${i} --> "$i" no error pops out, but also nothing happens enter image description here

CodePudding user response:

If the goal is to only write the mv command once then a sensible solution would be:

for i in 1 2
do
    mv "A$i"* "new$i/"
done
  • Related