Jump to content

Bash script for moving multiple files to multipe directories


Recommended Posts

Posted

Hello,

I recently started learning bash and had an idea how to make my life easier with one script, but now I am just pulling my hair with frustration because I can't think of any idea how to exactly do it, so maybe you guys can help me out with this.

So what I want to do is that I have one directory with like ~600 .pfd files in it and I want to split(or move) all these files to different directories.

I will just write and example which will allow you to understand what i want to do.

 

Lets say all my files are stored in:

/home/user/Desktop/list

and i have another dir on desktop (lets say it's /home/user/Desktop/Result ) which contains folders like: Item001, Item002, Item003 etc...

 

All i want to is to take first .pdf from (/home/user/Desktop/list) and move it to folder (/home/user/Desktop/Result/Item001) and the take second .pdf and move it to (/home/user/Desktop/Result/Item002) and so on.

 

#!/bin/bash
cd /home/user/Desktop/list
i=0
while read line
do
   array[ $i ]="$line"        
   (( i++ ))
done < <(ls -R)
echo ${array[1]}
mv "${array[1]}" /home/user/Desktop/Result/Item001

 

I managed to make a little script which is almost doing what i need, but i do not know how to make this line (

mv "${array[1]}" /home/user/Desktop/Result/Item001

) to add like +1....

 

I know that this probably very noobish-like way of doing it but as i said i just started learning bash and i am not very much experienced in programing at all. :)

 

Hope someone can enlighten me on this thing.

 

Thanks in advance.

Posted (edited)

It's a bit old skool, but should work.

 


COUNTER=1

for f in /home/user/Desktop/list/*
do
   PREFIX=
   if [ $COUNTER -lt 100 ]; then PREFIX=0; fi
   if [ $COUNTER -lt 10 ]; then PREFIX=00; fi  #should use an else but meh...
   echo $PREFIX
   echo $PREFIX$COUNTER
   
   mkdir /home/user/Desktop/Result/Item$PREFIX$COUNTER
   mv $f /home/user/Desktop/Result/Item$PREFIX$COUNTER
   let COUNTER=COUNTER+1
   
done

Edited by jinnantonnixx
  • Thanks 1
Posted

wow that was fast.. :)

only had to add ""

mv "$f" /home/user/Desktop/Result/Item$PREFIX$COUNTER

on $f variable because there are spaceses in file name.

but anyway THANK YOU!!!

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now



×
×
  • Create New...