[ale] Keep space separated values sane in a bash "for" loop?
aaron
aaron at pd.org
Thu Apr 5 20:13:06 EDT 2007
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:
=====
#!/bin/bash
# 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"
OTAG=".mp3"
for TAG in $TAGS
do
ls -1 | grep "$TAG$" |
while read IFYL
do
OFYL=${IFYL/%$TAG/$OTAG}
echo "Encoding \"$IFYL\" to \"$OFYL\" "
lame -b 192 "$IFYL" "$OFYL"
done
done
exit 0
====
To do the same basic thing reading lines
from a text file the syntax is:
while read LINEFROMEFYL
do
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.
;-)
peace
aaron
More information about the Ale
mailing list