[ale] SOLUTION Re: Keep space separated values sane in a bash "for" loop?

Robert Story rstory-l at 2006.revelstone.com
Fri Apr 6 12:27:26 EDT 2007


On Fri, 6 Apr 2007 12:18:08 -0400 Robert wrote:
RS> On Thu, 5 Apr 2007 20:13:06 -0400 aaron wrote:
RS> A> Here's technique that might help. I whipped this up for dealing with
RS> A> spaced names common to audio file that I wanted to batch convert
RS> A> to mp3.  Works with bash on Mac -- should work with Linux bash as
RS> A> well. The trick was to pipe the file listing to READ from STDIN instead
RS> A> of letting a FOR loop parse the input:
RS> 
RS> This works great for embedded spaces, but not so much for spaces at the
RS> beginning or end of a file name...


I've had this same problem for a while, and have always done manual clean-up.
After trying these solutions and reading the ls man page, I now have a working
solution that handles spaces anywhere in the name.

#!/bin/bash
oldifs=$IFS
export IFS=","
for i in `ls -m|sed 's/, /,/g'`
do
   echo \"$i\"
done
export IFS=$oldifs


Of course, the above will break for files with a ',' in them, but I can live
with that... the paranoid could add an initial ls|grep to check and warn for
that case...



More information about the Ale mailing list