Thursday, 11 February 2016

How To Rename Multiple Files In Unix/Linux

Let say we have below file in home directory /home/baba

$ ls -ltr


-rw-r--r--  1 baba None   9 Jan 26 14:11 A1.txt
-rw-r--r--  1 baba None  32 Jan 26 14:20 A2.txt
-rw-r--r--  1 baba None  32 Jan 26 14:20 A3.txt
-rw-r--r--  1 baba None  10 Jan 26 14:20 A4.txt
-rw-r--r--  1 baba None  92 Feb  2 22:38 A5.txt
-rw-r--r--  1 baba None 278 Feb  2 22:43 A6.txt

We want to rename all these files and want to concatenate _bkp in file name

#!bin/sh
for i in `ls`
do
echo "Current File Name is...:"${i}
mv ${i} ${i}"_bkp"
done

Output:Will rename all the objects in the current directory by concatenating _bkp

We can archive the multiple files in one go by keeping the original fles, for example we want to keep archive of files in archive directory.

#!bin/sh
for i in `ls`
do
echo "Current File Name is...:"${i}
cp ${i} /home/baba/Archive/${i}"_bkp"
done

Output:
cp command will create a copy of the existing file in archive directory and will keep the original file in same directory.


Always use the path while reading the file name in for loop instead of giving only ls command.

#!bin/sh
for i in `ls /home/baba`
do
echo "Current File Name is...:"${i}
mv ${i} /home/baba/Archive/${i}"_bkp"
done


Output: Above all command will rename all the files from /home/baba and move it to /home/baba/Archive/ directory.

-rw-r--r--  1 baba None   9 Feb 12 14:11 A1.txt_bkp
-rw-r--r--  1 baba None  32 Feb 12 14:12 A2.txt_bkp
-rw-r--r--  1 baba None  32 Feb 12 14:13 A3.txt_bkp
-rw-r--r--  1 baba None  10 Feb 12 14:15 A4.txt_bkp
-rw-r--r--  1 baba None  92 Feb 12 14:30 A5.txt_bkp
-rw-r--r--  1 baba None 278 Feb 12 14:40 A6.txt_bkp

Keep Reading, Keep Learning, Keep Sharing.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...