-   Programming (
-   -   renaming files recursively by replacing a character in filename (

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: : somename.html
I would like to replace the : by a dash i.e - as shown below

Code: - 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 '-' ?


# 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


rename : -*
This works, but not recursively.

Thanks in advance.

radoulov 04-29-2007 08:53 AM

With bash:


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

With zsh:


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:


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

ghostdog74 04-29-2007 09:50 AM

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

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(":" ,"-")))       

etechnophile 05-04-2007 11:26 PM

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 11:39 PM.