Reading a listing of files in Bash and want to remove spaces from filename

Hi guys,

I'm reading the files in a directory using the script below but the problem is when a file has a space inside of it for example a file named "New_ Extel File.xlsx". The script reads the one file name as three seperate files such as New_ is one file Extel is anotehr file and then File.xlsx is the third file. Is there anyway to get rid of the spaces so that filename is read as one filename instead of 3? Is there a way to do this in Perl if not bash??

#!/bin/bash

cd /tmp/testing2
for i in `ls`; do
  echo ${i//[[:space:]]}
done

Open in new window

TbalzAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

woolmilkporcCommented:
You could set the internal field separator to the empty string.
Besides that you should delete "blank" instead of "space" to keep the line feeds (if this is still necessary, that is, you can often work with filenames containing spaces, depending on what you're trying to achieve).

#!/bin/bash
IFS=""
cd /tmp/testing2
for i in `ls`; do
  echo ${i//[[:blank:]]}
done
0
TbalzAuthor Commented:
Actually this worked wonderfully.

#!/bin/bash

ls | while read -r FILE
do
    mv -v "$FILE" `echo $FILE | tr ' ' '_' | tr -d '[{}(),\!]' | tr -d "\'" | tr '[A-Z]' '[a-z]' | sed 's/_-_/_/g'`
done

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
woolmilkporcCommented:
Actually, what are you going to do with those blurred filenames? Why not use them as they are?
You'll just need a bit quoting.

ls | while read -r FILE
do
   echo "$FILE"
   # do with "$FILE" whatever you want
done
0
TbalzAuthor Commented:
I was able to find the solution on my own.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Linux

From novice to tech pro — start learning today.