Script move files by name

hi,

I have a lot of files named xxxxx__AA.txt, xxxxx__BB.txt, xxxxx__CC.txt and I would like to move xxxxx__AA.txt in AA directory, xxxxx__BB.txt in BB etc. Could you help me do it in bash script?

Since you are dealing with lots of files lets sort them out first, so you can validate what the code will do. This makes a script in /tmp. READ the script first to be sure mv is not overwriting something. Change the code below to match the directory name.

#!/bin/bash

SCRIPT=/tmp/mv_script.sh
cd /home/jim                      # change this path 
echo "cd `pwd`" > $SCRIPT

ls | awk '{
          if( $0~/_[A-Z]{2}.txt$/)
             {                  
                   f=substr($0,length($0)-5,2)                   
                   printf("[ -d %s ] || mkdir %s\n", f, f)
                   printf("mv %s ./%s/%s \n", $0, f, $0)            
             }               
        } ' >> $SCRIPT
chmod +x $SCRIPT        
#!/bin/bash
while read i
do
     mkdir $(echo ${i:6:2}) && mv $i $(echo ${i:6:2})
done < <(ls |awk --posix '$0~/[A-Z]{2}.txt$/')

Try shell-only:

printf "%s\n" *__*.txt | 
while IFS='_.' read name x kind suffix
do
  mkdir "$kind" 2>/dev/null
  mv "${name}__${kind}.${suffix}" "$kind"
done

Thanks a lot! I tried all of them but i could not do working. Could you help me please.

Hi Corfuiti,

Can you supply the directory structure, from the directory at the top level. If the files are at the level above the directories, this is quite straight forward using something like find.

Regards

Dave

1 Like