Self-hatred

[Bash] Batch renaming files

Despite (or perhaps because of) the fact I’ve been using Linux for more than a decade, I’ve done a great job of avoiding sed. I have done my best to make up for it in the recent past by learning how to at least find and replace, either within a file or in a filename. Here is how you batch rename files using sed in a Bash shell.

To rename all *.txt files in a directory (in this case to replace any spaces with _.

for file in *.txt; do mv "$file" "$(echo $file | sed -e 's/ /_/g')"; done

To unpack:

for file in *.txt

For each text (.txt) file in this directory.

do mv "$file"

Move the file from it’s current name to

"$(echo $file | sed -e 's/ /_/g')"

this. In this second part, we echo the name of the file and pipe the name into sed. The syntax for find and replace in sed is: sed -e 's/foo/bar/g where foo is the old string and bar is the new string. You echo the file name, and simply replace the ” ” with “_”.

I sincerely hope this is useful to somebody, somewhere.


Categorised as: linux, programming


Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>