LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   renaming files recursively by replacing a character in filename (http://www.linuxquestions.org/questions/programming-9/renaming-files-recursively-by-replacing-a-character-in-filename-549897/)

etechnophile 04-29-2007 07:12 AM

renaming files recursively by replacing a character in filename
 
I have many files which have filenames of the format

Code:

nameofwebsite.com : somename.html
I would like to replace the : by a dash i.e - as shown below

Code:

nameofwebsite.com - somename.html
I searched LQ and found a script that does the job recursively, but it's for replacing spaces by underscores. Since I don't know sed at all, can someone help me modify this script for replacing ':' by '-' ?

Code:

#!/bin/bash
# Recursive replacement of spaces with "_" in files/dirs
[ $# -ne "1" ] && echo "Usage: $0 <dir-path>" && exit 1
find $1 -name "* *" | sed 's/^.*$/mv \"&\"/g' > t1$$
find $1 -name "* *"|sed -e 's/ /_/g' -e 's/^.*$/\"&\"/g' >t2$$
paste t1$$ t2$$ > t3$$; sh t3$$; #rm -f t?$$
#[t?$$ files will help you in an accidental action]

Any other way to do this will be appreciated too. I initially tried

Code:

rename : - nameofwebsite.com*
This works, but not recursively.

Thanks in advance.

radoulov 04-29-2007 08:53 AM

With bash:

Code:

find . -name "* : *.html"|
        while IFS= read -r;do
                mv "${REPLY}" "${REPLY/ : / - }"
        done

With zsh:

Code:

autoload -U zmv
zmv '(**/)(* : *).html' '$1${2/ : / - }.html'


P.S. The bash solution, of course, will fail, if you have the same pattern somewhere in the path or more than once in the filename and you want to change not the first one (in the latter case both zsh and bash solutions will fail).
In the first case something like this will be more appropriate:

Code:

find . -name "* : *.html"|
        while IFS= read -r;do
                fpath="${REPLY%/*}/"
                fname="${REPLY##*/}"
                mv "$REPLY" "${fpath}${fname/ : / - }"
        done


ghostdog74 04-29-2007 09:50 AM

If you have Python, here's an alternative. It recurses the current directory
Code:

for r,d,f in os.walk("/startdir"):   
    for file in glob.glob(os.path.join(r,"*.html")):
        filename = os.path.split(file)[-1] 
        if ":" in filename:     
            newfile = "%s" % (os.path.join(r,filename.replace(":" ,"-")))       
            os.rename(file,newfile)


etechnophile 05-04-2007 11:26 PM

Thanks
 
I can't try out any of these solutions right now since I'm away from my PC at the moment, but will try them out as soon as possible. Thank you radoulov and ghostdog74 for the fast replies.


All times are GMT -5. The time now is 12:25 AM.