Search code examples
linuxbashwhitespace

Replacing both spaces and " - " in filenames and directorys


I have been reading this this discussion and this find . -depth -name '* *' \ | while IFS= read -r f ; do mv -i "$f" "$(dirname "$f")/$(basename "$f"|tr ' ' _)" ; done
helps me deleting spaces in files and directories.
Beat Boy becomes Beat_Boy. This is ok.
What I don't get right is how to deal with this:
Beat Boy - Best of becomes Beat_Boy_-_Best_of while I want it to be Beat_Boy-Best_of.
I would appreciate any hint which way to go...

Regards


Solution

  • You can add sed to substitute "_-_" with "-"

    f="Beat Boy - Best of"
    
    echo $f | tr ' ' _ | sed 's/_-_/-/g'
    #Beat_Boy-Best_of
    

    In your case, you would want:

    find . -depth -name '* *' | 
        while IFS= read -r f ; do 
            mv -i "$f" "$(dirname "$f")/$(basename "$f" |
                tr ' ' _ |
                sed 's/_-_/-/g')" ; 
        done
    

    Edit

    You can also replace tr ' ' _ | sed 's/_-_/-/g' with sed 's/ /_/g ; s/_-_/-/g'.