Moving files based on file name

Hi All,

I have multiple files in the folder, I want to move those files into the other folder on based of name

File names:

Template_server1_01==>
Template_server1_02==>To one directory /Server1
Template_server1_03==>

Template_server2_01==>
Template_server2_02==>To one directory /Server2
Template_server2_03==>

On the basis of server name in the file name , need to move it to the particular directory.

Try,

mv Template_server1* Server1
 
mv Template_server2* Server2

Make sure you created Server1 and Server2 directories in the same path.

Actually directories is at differnt path, like:

/home/username/temp/hosts/server1
/home/username/temp/hosts/server2
i=1;
while [ i -le 10 ]
do
mv *server$i* /home/username/temp/hosts/server$i
i=$(expr $i + 1)
done

Thanks Pikk

Let me reiterate my request.

Server1 is just i put it randomly, Actually name of the server will be like cetiss, nik.tikkr etc. and name will be differnt. So if file name contains citiss it will be into /home/username/temp/hosts/citiss

so the filename format is the same as what you mentioned? Please specify your req correctly otherwise we would end up doing guess work and you will never get the desired answer :slight_smile:

if server name is at field 2 (underscroe _ seperated)

 
for file in * ; do
dir_name=`echo $file | awk -F_ '{print $2}'`
# Create directories here if they are not there already
mv $file /home/username/temp/hosts/${dir_name}
done

I will take your advice Vidyadhar,

File name is Monitor_Template_citiss-7444

Need to check for citiss and move the file

hey try this if it works. sorry i am late.. i am new to shell scripting so little bit slow..

u may need to change some paths according to ur locations.
like

ls -ltr $path

and

mv $files $absolutePath/$server_name
ls -ltr | grep "^-" | awk '{print $NF}' >> file_move.lst
server_list="cetiss nik.tikkr"
server_list=($server_list)

for server_name in "${server_list[@]}"; do

        files=`grep $server_name file_move.lst`
        mv $files ./$server_name

done

Thanks Little for your efforts.

In my last post I have given the exact file name. I will be having two (_ underscore) in the filename.

then try with 3

 
for file in * ; do
dir_name=`echo $file | awk -F_ '{print $3}'`
# Create directories here if they are not there already
mv $file /home/username/temp/hosts/${dir_name}
done