[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

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

On Thursday 05 April 2007 19:59, Christopher Bergeron wrote:
> Guys, I'm not sure how to word my question appropriately, so I'll try to 
> explain what I'm trying to do in code.
> I have a bash for loop, and when it encounters a value with a space, it 
> splits it into separate entities.  For example:
> With a file list of:
> /bin
> /usr
> /Virtual Machines
> and a code snippet of:
> for i in *; do
> echo "Filename is: $i"
> done
> The output is:
> Filename is: bin
> Filename is: usr
> Filename is: Virtual
> Filename is: Machines
> How can I tell bash to keep these values together, so that I get the 
> filenames intact as:
> Filename is: bin
> Filename is: usr
> Filename is: Virtual Machines

Hey Chris!

Here's technique that might help. I whipped this up for dealing with
spaced names common to audio file that I wanted to batch convert
to mp3.  Works with bash on Mac -- should work with Linux bash as
well. The trick was to pipe the file listing to READ from STDIN instead
of letting a FOR loop parse the input:
# Creates new mp3 encoded files for all standard
# .aif, .aiff and .wav TAGged files found in current directory

TAGS=".aif .aiff .wav .AIF .AIFF .WAV"
for TAG in $TAGS
   ls -1 | grep "$TAG$" |
   while read IFYL
      echo "Encoding \"$IFYL\" to \"$OFYL\" "
      lame -b 192 "$IFYL" "$OFYL"

exit 0
To do the same basic thing reading lines
from a text file the syntax is:

   echo "$LINEFROMFYL"
done </mypath/mytextfile

You can also take an aproach of changing the white space
seperator environment variable that bash uses to change the
way an instance of the shell does it's parsing, but that may be
more messy fun than necessary.