Pages

Friday, February 24, 2012

How to remove/replace a given character/word from all the filenames in current directory using sed

#!/bin/bash
extension="txt"
for files in *.$extension; 
do 
    mv $files `echo $files | sed 's/B/A/g'`; 
done;
 
The mv command is used to rename the files.

sed parses the filename and replaces all the occurrences of "B" character with "A".

eg. BAOBAB.txt will be replaced by AAOAAA.txt

The script is case sensitive. Also, be careful with special characters that need to be escaped with "\".
For example if you have a file called ^name.txt and want to replace "^" character from the filename with "A", using the command:

mv $files `echo $files | sed 's/^/A/g'`;  

will lead to the following output:

A^name.txt

You need to escape "^" character:


mv $files `echo $files | sed 's/\^/A/g'`;

In this case the output will be:

Aname.txt

This script also works if you use words instead of characters.

0 comments:

Post a Comment