Bulk rename of files in unix

Wednesday, January 09, 2013 , , , 0 Comments

Most of the time it is required that w eneed to rename the files in bulk.
this can be done in many ways,Mostly people do it by writing a simple shell script.

I found a better way to do it using just the command line in a single command.
Let's say we have some files as shown below.Now i want remove the part -(ab...) from those files.
> ls -1 foo*
foo-bar-(ab-4529111094).txt
foo-bar-foo-bar-(ab-189534).txt
foo-bar-foo-bar-bar-(ab-24937932201).txt
So the expected file names would be :
> ls -1 foo*
foo-bar-foo-bar-bar.txt
foo-bar-foo-bar.txt
foo-bar.txt
Below is a simple way to do it.
> ls -1 | nawk '/foo-bar-/{old=0ドル;gsub(/-\(.*\)/,"",0ドル);system("mv \""old"\" "0ドル)}'
Explanation:

ls -1
Will list all the files in a single column in a directory

nawk '/foo-bar-/ 
The processing is done only for a file names with has foo-bar- as a part of their names.

old=0ドル 
initially storing the file name in a variable.
gsub(/-\(.*\)/,"",0ドル) 
Removing the undesired part of the file name.

mv \""old"\" "0ドル 
This will be expanded to :mv "foo-bar-(ab-4529111094).txt" foo-bar-foo-bar-bar.txt.You might ask why a '"'.because there is possibility that the fine name might consist a space or any other special character(in our case it has '(' ).

system("mv \""old"\" "0ドル) 
This will execute on teh command line what ever is there inside the system call.

Note: nawk is specific for solaris unix.for other falvours of unix just awk is enough.

0 comments:

Subscribe to: Post Comments (Atom)