Replace spaces recursively

Hi,

I have a directory with files and sub-directories (sub-directory depth might go upto 5). There will be one or more spaces (continuously or anywhere in the file name) which need to be replaced with HYPHENs. How can i replace all SPACE occurances with HYPHEN in file/dir names recursively. (2 or more continuous occurances of SPACES should be replaced with SINGLE HYPHEN).

Thanks
Prvn

Try This:

find . -name "*" | sed '1,$s/ /\-/g; s/\-\-/\-/g'

Waseem,

This will not rename the file. Option is to write a script with a combination of find ,sed and mv command.

Cheers,
K

I know it will not rename the file but it will only generate the list of filenames as expected. a simple mv can be performed after getting the list from my previous command.

Thannks kamitsin and Waseem.

Kamitsin, yours offer recursive solution and yes, i will use mv to achieve the rest.

I need small addon to my requirement (sorry, i did not mention earlier) that LEADING and TRAILING spaces should be removed (not to be replaced with HYPHEN). In other words, file/dir names should not start/end with HYPHENS e.g. if a file with name
" m n " to become "m-n".

Txs
Prvn

If you have Python and is able to use it as an alternative:

#!/usr/bin/python
import os,re
for root,dir,files in os.walk("/test"):
    for fi in files:
        if fi.count(" ")>0:
            fi=fi.strip()
            newfile = os.path.join(root,re.sub("\s+","-",fi))
            os.rename(os.path.join(root,fi),newfile)