LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   please help me remove the spaces in filenames in a directory! (https://www.linuxquestions.org/questions/linux-newbie-8/please-help-me-remove-the-spaces-in-filenames-in-a-directory-463926/)

asilentmurmur 07-14-2006 03:25 AM

please help me remove the spaces in filenames in a directory!
 
Hey everyone

I recently copied a folder over from my Winbl0wz partition. I noticed that many of the files have spaces in their file names. Do you all know of any scripts that i could use to remove all the spaces in the names of files contained in a directory? All help is GREATLY appreciated in advance!

unSpawn 07-14-2006 04:51 AM

Not onehundred percent trouble free so YMMV(VM):
Code:

find /home/asilentmurmur/windowsdir -type f | while read f; do mv "${f}" "${f// /_}"; done
BTW, try searching LQ, we definately have similar solutions, probably in the Programming forum.

spooon 07-14-2006 05:03 AM

how about
Code:

find /home/asilentmurmur/windowsdir -type f -execdir rename '" "' '""' '{}' \;

bushidozen 07-14-2006 07:17 PM

If you have python installed try this:
Code:

#!/usr/bin/python
# the following script will traverse through all of the files
# within the directory where it is placed and replace each
# space within the filename with an underscore

import os, sys
if len(sys.argv) == 1:
    filenames = os.listdir(os.curdir)
else:
    filenames = sys.argv[1:]
for filename in filenames:
    if ' ' in filename:
        newfilename = filename.replace(' ', '_')
        print "Renaming", filename, "to", newfilename, "..."
        os.rename(filename, newfilename)

place the code in a text file (with a .py extension), make it executable, place it in the directory whose files you wish to change, and either run it from the command line (python name-of-file.py) or just click on it.

If you want to do it in bash, try this:
Code:

for i in *; do mv "$i" "$(echo $i | tr ' ' '_')"; done
or this:
Code:

for i in * *; { mv ''$i'' $(echo $i | sed 's/ /_/g'); }
or this (this one is recursive):
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]

just cd to the directory and type one of the above. It should work, but I think the python code is a little faster.


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