Link to home
Start Free TrialLog in
Avatar of Tbalz
Tbalz

asked on

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

Avatar of woolmilkporc
woolmilkporc
Flag of Germany image

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
ASKER CERTIFIED SOLUTION
Avatar of Tbalz
Tbalz

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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
Avatar of Tbalz
Tbalz

ASKER

I was able to find the solution on my own.