Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Renaming files to eliminate whitespace

Status
Not open for further replies.

lnewsome

Technical User
May 9, 2001
3
US
I have a list of 14,000 files on my Solaris box that contains whitespace.

ex. red sound 345.wav
red soundloud345.wav
gt564 sound.wav

I need to change all the whitespace to _.

ex: red_sound_345.wav
red_soundloud345.wav
gt564_sound.wav

How would I do this? Any help would be tremendously appreciated.
 
Try this using sed.

#!/bin/csh
if(-f $1) then
cd $1
foreach i (*)
set newname = `echo $i | sed s/\_/ /g`
mv "$i" $newname
end
else
endif
 
Hmmm. I tried it but I it does throw an error:
if: Expression syntax

Or am I doing something wrong?

./whitespacescript *.*

 
Hi Inewsome,

This awk script wrapped in a shell file seems
to do the task you need done.

However, I would create a test directory and some
test files by using the touch command to create
some zero length files. Then, test this script to be
sure it does what you expect *BEFORE* you commit
your real files!

#!/bin/sh

ls -1 *.wav > $1

touch final

chmod +x final


awk 'BEGIN{FS=OFS=""}

{
gsub(/\ /,"\\\ ",$1)
file = $1
gsub(/\\ /,"_",$1)
newfile = $1
line = sprintf("mv %s %s", file, newfile)
print line >> "final"
}
END { close("final")
system("final")
}' $1

Note- $1 on command line will be your input file
that is constructed by putting all the files that end
in ".wav" into it. The file "final" is created and
made executable by the shell script. The awk
script will build a series of move ("mv") commands,
one for each file in the input file. The END line
in the awk script closes final, then, opens it and
launches the "mv" commands it contains, effectively
renaming the files that contained the spaces.

Hope this helps you!


#rm $1 final


flogrr
flogr@yahoo.com

 
Inewsome,
Here are two ways you can do it. The first one uses the tr command or
you could manipulate it with sed (use sed 's/\ /_/g' instead of the tr command).
The second one with awk manipulates the filename so you have multiple variables in the filename.

for file in *" "*
do
new=`echo $file | tr " " "_"`
mv "$file" "$new"
echo "$new"
done


***********************************************************



#!/bin/ksh
for c in `ls *" "* | awk '{ OFS="_" } { print $1, $2 }'`
do
echo $c
a=`echo $c | awk -F_ '{print $1}'`
b=`echo $c | awk -F_ '{print $2}'`
mv "$a $b" $c
done
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top