6V8 - Production of my Mind

Home page > For your Computer > Mass renaming with linux shell

Mass renaming with linux shell

 

When you do mv *.aaa *.bbb, it’s not obvious to a newbie that it won’t work.

The solution is a bit more tricky and needs piping (|) and sed.

23 September 2003, by Mortimer

1Renaming

So, if you wanted to rename all the .php3 to .php, this would be the command:

ls -d *.php3 | sed 's/\(.*\).php3$/mv "&" "\1.php"/' | sh

so what does this do?

  • ls -d *.php3 outputs a list of all the php3 files in the directory. This list is piped to the second command,
  • sed ’s/\(.*\).php3$/mv "&" "\1.php"/’ is not as obvious for newbies. sed is a tool to edit stream. Here the stream is the list of files. the argument passed to sed ’s/\(.*\).html$/mv "&" "\1.php"/’ is what should be edited:
  • s tells sed to replace a string by another,
  • (.*\).php3$ is a regular expression to tell that the string we will want to replace is anyname.php3,
  • mv "&" "\1.php" is the replacement string. the \1 is there to take the name of the file in the first string and put it there. & refers to the portion of the pattern space which matched,
  • | sh takes the output of sed and executes it (sh is the shell interpreter). hence executing the list of mv anyname.php3 anyname.php.

2Anything

In fact this trick could be used for anything. The sole part that will change would be the replacement string in the sed command.

Then if you want to replace all the php3 references in a file by php you’ll use:

sed 's/\.php3/.php/g'

so for a mass replacement, the command would be:

ls -d *.php3 | sed 's/\(.*\).php3$/sed "s\/\\.php3\/.php\/g" "&" > \1.php' | sh

remark that you have to escape all the / and \. And that in the same time we will rename the files to php :).

Date of online publication: 23 September 2003
last-update: 11 May 2004
All the versions of this article:
Forum messages 7
visits:
25924

Creative Commons Attribution NonCommercial ShareAlike 2.5  License
 

Reply to this article

7 Forum messages

 

The most read articles

Photos On Flickr

 
©
Pierre Andrews
York, uk
| Site Map | Site created with SPIP 1.9.2d [11132] | RSS | template by IZO, Mortimer. |
created published documented and claimed
created published documented and claimed
created published documented and claimed
created published documented and claimed
created published documented and claimed