Use sed to change multiple filenames

| 1 Comment


I wanted to replace all hyphens in all filenames starting with 2003- and ending with .php. Here's how I did it using sed (no guarantees, no warranties, use at your own risk!):

  1. Backup the files!
  2. Change to the directory you want to make the changes in.
  3. Then, to make sure the right filenames will be changed, list the filenames using the following sed command (modify "2003-*.php" and the sed search and replace strings for your situation):

    for filename in 2003-*.php; do echo $filename | sed \e 's/\-/\_/g'; done

  4. When you're sure the above sed command is listing the right filenames, change it as follows (modify "2003-*.php" and the sed search and replace strings for your situation):

    for filename in 2003-*.php; do newname=`echo $filename | sed \e 's/\-/\_/g'`; mv $filename $newname; done

Note the use of the backtick character (`) (also known as backquote) which, on my keyboard, is located to the left of the "1" key. The backtick character is used in addition to the single quote character (').

[Update January 4, 2009] I totally forgot that I could have used the "rename" command instead of sed! There is control over which underscore in a filename is changed. More about renaming files using "rename".

1 Comment

thanks! this is perfect. exactly what i was looking for. thanks for sharing!

Leave a comment

Sketch of Cheryl

About Cheryl

Enjoys crocheting, gardening, cats, NASCAR (especially Tony Stewart and Kyle Busch!), reading, photography, snorkeling in Kailua-Kona with sea turtles, Sizzler's Mega Bacon Cheeseburgers, hot and iced decaf coffee, dark chocolate, color (yarn, fabric), playing around with web technologies - not necessarily in that order! Still very much a beginner with quilting, knitting, and sewing. Donates crocheted lap blankets.

List maker, detail-oriented, organized, leans heavily toward perfectionism. ISTJ. Libra.

January 2017

Sun Mon Tue Wed Thu Fri Sat
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31        
Disclaimer: This is a personal website - my place of self expression. The views expressed are mine alone and do not necessarily reflect the views of my employer or any other organization I am a member of or affiliated with.
Creative Commons License
This blog is licensed under a Creative Commons License.
Powered by Movable Type 5.2.2

About this Entry

This page contains a single entry by Cheryl published on January 2, 2009 5:45 PM.

Quilt Block Curtains was the previous entry in this blog.

Recipe: Taco / Burrito / Nacho Mix is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.

Cat playing with strand of yarn.

Categories





Recent Comments

  • kamgrn: thanks! this is perfect. exactly what i was looking for. read more
HERE1 HERE2