Bulk rename of files in unix

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*
So the expected file names would be :
> ls -1 foo*
Below is a simple way to do it.
> ls -1 | nawk '/foo-bar-/{old=$0;gsub(/-\(.*\)/,"",$0);system("mv \""old"\" "$0)}'

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.

  initially storing the file name in a variable.
 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.

No comments:

Post a Comment