Operating System - HP-UX
1833157 Members
3178 Online
110051 Solutions
New Discussion

Re: rename files with blanks

 
SOLVED
Go to solution
Wolfram Knorr
Occasional Advisor

rename files with blanks

HI all,

i have a bunch full of files which are named like this:
123 456 789.txt between each block a blank.
i`d like to rename them to 123456789.txt

I tried to ls them in a txt-file, but if i use a loop it can`t find the files because of the separation in the filename

I wrote a loop like this:
for i in `ls *`
do
echo $i
done

the output is shown
123
456
789.txt

The same if i use quotes on the filename "123 456 789.txt"

the ouptup is the same like above
for i in `ls "*"`
do
echo $i
done

123
456
789.txt

Please , down on my knees ;-) , HELP
I have to rename around 2500 files

THanks for all your comments.
resistance is futile
6 REPLIES 6
Mel Burslan
Honored Contributor
Solution

Re: rename files with blanks

ls -1 | while read filename
do
newname=`echo $filename | sed -e "1,1s/\ //"`
mv "$filename" "$newname"
done


Hope this helps
________________________________
UNIX because I majored in cryptology...
Mel Burslan
Honored Contributor

Re: rename files with blanks

small ooops. Forgot to put the "g" at the end of sed script. first version will only remove the first blank. This, below, removes all.

ls -1 | while read filename
do
newname=`echo $filename | sed -e "1,1s/\ //g"`
mv "$filename" "$newname"
done
________________________________
UNIX because I majored in cryptology...
Leif Halvarsson_2
Honored Contributor

Re: rename files with blanks

hi,
try a simple sloution as

ls |while read a b c
do

echo $a$b$c

done
Wolfram Knorr
Occasional Advisor

Re: rename files with blanks

HI guys,

thanks i worked .

Still on my knees , head on the floor.

Points are on the way


resistance is futile
Wolfram Knorr
Occasional Advisor

Re: rename files with blanks

thread closed
resistance is futile
A. Clay Stephenson
Acclaimed Contributor

Re: rename files with blanks

You really need to make sure that the new filename does not exist before doing the mv. The key to reading whitespace is quoting and you should really quote all pathnames because whitespace is perfectly legal (if dumb) in pathnames.

#!/usr/bin/sh

typeset -i ${STAT}=0
typeset F=''
typeset F2=''
ls *.txt | while read F
do
echo "File: \"${F}\" \c"
F2=$(echo "${F}" | tr -d ' ')
if [[ "${F}" != "${F2}" ]]
then
if [[ -e "${F2}" ]]
then
echo "File ${F2} exists; cannot mv." >&2
else
echo "-> ${F2}\c"
mv "${F}" "${F2}"
STAT=${?}
if [[ ${STAT} -ne 0 ]]
then
echo "Mv failed; status ${STAT}" >&2
break
fi
fi
fi
echo
done
exit {$STAT}
If it ain't broke, I can fix that.