Renaming batches of files

If you’re coming to BeOS from the DOS world, you expect Terminal to be a lot more powerful than DOS. And it is. But with power comes an occasional price — some things are more complex to accomplish in bash than in DOS. A good example of this is in renaming large batches of files. Let’s say you’ve got a directory containing 500 text files, all ending with the .txt extension, and you want to make them end in .html. In DOS, this would be as simple as typing ren *.txt *.html. Since the bash command for renaming files is mv, you might expect you can type mv *.txt *.html. But it doesn’t work that way.
It would take a complex explanation of exactly how the bash shell works to explain why not, but if you need to accomplish this task, here’s how: type the following into the shell, hitting Enter after each line.

for i in *.txt
mv "$i" "$(echo $i | sed s/.txt$/.html/)"

In a nutshell, here’s what’s going on: you establish a loop to go through all the filenames in the current directory ending in .txt (* refers to all files in the current directory). „Do“ means you’re going to look at the first file and do something with it. That something is the move command, mv. We move the first file from its current location of {variable} to {variable.html}. The tricky part is that we need to use sed (the stream editor) to substitute the string „txt“ at the end of the line with the string „html“. Done means we’re ready to move to the next file, and also serves as a flag for the process to exit when all files have been processed.
If you need to use this function frequently, save the whole block as a script prefaced with the magic cookie #!/bin/sh and call it „ren“ or something else intuitive.
Note that just changing the extensions will not change the filetypes, because BeOS doesn’t use extensions as its primary means of identifying filetypes. To do that, see the tip Batch-changing filetypes.



No comments so far.

(comments are closed)