[svlug] Working with spaces in shell scripts

Andrew a at t.armory.com
Tue Dec 14 15:55:44 PST 2004

On Tue, Dec 14, 2004 at 03:15:15PM -0800, Nathan wrote:
> I want to remove the some files from inside a bunch of directories with
> spaces in the names. But when my script hits a directory with a space in
> its name the script will treat it as two separate directories (ie
> "Monkey Joe" becomes "Monkey" and "Joe"). Can this even be done with a
> shell script? Should I break down and use perl? 

Theres a few things you can do, 

ls|while read line; do rm "$line"; done will work, theres many other
variations, the read will read an entire line, so long as your ls prints
one file per line (which it will do in a pipe) it should be fine.

Alternatively you can change IFS to include on \n, then do
for each in $(ls); do 
rm $each
I dont like changing IFS, its error prone.

You could also do this:
ls|while read line; do
echo "\"$line\""
done|xargs rm

That will quote each line (same thing can be done with IFS + for each),
the advantage of that is fewer invocations of rm, the xargs bundles the
args up into 32k bundles.

I've also written little sed, awk and perl commands to quote each line,
then put it in the pipeline with xargs instead of the loop in the shell

These seem to work last i tried:
sed 's/^/\"/;s/$/\"/'
perl -lne'print"\"$_\""'
awk '{print "\"" $0 "\"";}'

Im sure theres even quicker ways to do this in each language, and with
fewer characters etc.

ls|sed 's/^/\"/;s/$/\"/'|xargs rm


More information about the svlug mailing list