LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   Using Sed to Rename A Group of Files (http://www.linuxquestions.org/questions/programming-9/using-sed-to-rename-a-group-of-files-723311/)

smithjb 05-03-2009 10:23 AM

Using Sed to Rename A Group of Files
 
Hello,

I have a lot of files on a Fedora 9 box that contains '+' in the middle of the file name and I would like to remove them. I believe this should be doable using sed. Here's what I've got so far:

Code:

ls -d *+* | sed 's/+//g'
This however returns the correct results, but if I do another ls, nothing was really changed.

What am I missing?

Thanks,

colucix 05-03-2009 10:37 AM

Using sed that way, you don't really rename the files, but you simply parse the output of the ls command. To change file names, you can try the rename command (from inside the directory you have the files with +):
Code:

rename "+" "" *

colucix 05-03-2009 10:43 AM

You can also use substring replacement in bash:
Code:

for file in *+*
do
  mv $file ${file//"+"/""}
done

or if you want to use sed:
Code:

for file in *+*
do
  mv $file $(echo $file | sed 's/+//g')
done


pixellany 05-03-2009 10:48 AM

SED processes whatever you give it, and displays it on "STDOUT"---by default, your terminal window. It does not change filenames---that is done with the "mv" command.

why "ls -d" ?

I think you need something like this:
for filename in *; do newname= $(sed 's/+//g' $filename); mv $filename $newname; done

To drill down in the directory tree, use "$(ls -R) instead of "*"

colucix 05-03-2009 10:50 AM

Quote:

Originally Posted by pixellany (Post 3528497)
To drill down in the directory tree, use "$(ls -R) instead of "*"

Maybe the OP does not want to descend into directories, hence the -d option to avoid directory listing. Maybe. ;)

smithjb 05-03-2009 10:00 PM

Thanks everyone for your help.

The following works on some of the files:

Code:

for file in *+*
do
  mv $file $(echo $file | sed 's/+//g')
done

But I have a several files like "Judge+++++ 1-23-98" which I receive:

Quote:

mv: target `1-23-98.DOC' is not a directory
Even if I try to also remove the space along with the '+' I receive:

Quote:

mv: target `Judge+++++1-23-98.DOC' is not a directory
Thanks!

Robhogg 05-03-2009 10:27 PM

The problem is that the space causes mv to see everything after it as a separate file (or directory) name (in both parameters). If you put double-quotes around the parameters, it will "protect" the space, and you may want to alter the sed command to take account of the multiple +'s and space:
Code:

mv "$file" "$(echo $file | sed 's/[+ ]*//g')"
You could also slap the person sending you these files with a wet fish, until they start using sensible file names :).


All times are GMT -5. The time now is 02:42 PM.