Thursday, February 3, 2011

3 different ways of renaming a group of files



  While dealing with multiple file operations, it is very common to have a scenario where we would like to rename to set of files, say set of txt files to some other extension, or a set of non-extension files to a new 
extension, etc. In this article, we will see 3 different ways to rename the files.

1. To rename a set of stand alone files to a .txt extension. Assuming the directory contains the files file1, file2 and file3.


Method 1:
   This is a straight forward method in which we write a simple for loop and change the exentsion through the mv command:
for i in *
do
  mv $i $i.txt
done
  The above snippet can either be run at the prompt or by putting it inside a file and running the file.

Method 2:
  In this, we will get the renaming done by editing a file in vi.
  a)  Re-direct the filenames to a file, say ls file* > a
  b) Open the file a in vi.
  c) In the escape mode, give the following command: :%s/.*/mv & &.txt/
  d) Save and quit the file.
  e) Run the file a:  sh a

  In the step c, what we do is , replace the line with "mv " and hence we form mv commands to be executed. And we get it done by simply running the file a.

Method 3:
  In this method, we use the find and sed command to get our renaming of the files done.
find . -name "file*" | sed 's/.*/mv & &.txt/' | sh
   In this above, find finds the files and the sed command prepares the move instruction. If you note carefully, the syntax is same as the one used inside vi. And the output of the sed is piped to sh command.

2. Let us see an extension of the above. To rename a set of .txt files(file1.txt, file2.txt, file3.txt) to .exe extension using the same above methods:

Method 1:
   This method is same as the above method 1. Here we use the basename command to get the filename alone without extension and then include a different extension during the mv command:
for i in *.txt
do
  x=`basename $i .txt`
  mv $i $x.exe
done
Method 2:
  In this, we will get the renaming done by editing a file in vi.
  a)  Re-direct the filenames to a file, say ls file* > a
  b) Open the file a in vi.
  c) In the escape mode, give the following command: :%s/\.txt$/\.exe/
  d) Save and quit the file.
  e) Run the file a:  sh a

  The same explanation as given above.

Method 3:
   In this method, we use the find and sed command to get our renaming of the files done.

find . -name "*.txt"|sed 's/\(.*\.\)\(.*\)/mv & \1exe/' | sh
   In this above, find finds the files and the sed command prepares the move instruction. If you note carefully, the syntax is same as the one used inside vi. And the output of the sed is piped to sh command.

Related Posts Plugin for WordPress, Blogger...

1 comment:

  1. Please explain in detail method no. 3. i didn't understand this complex expression .

    ReplyDelete