From: sandy on
I want to write a bash script (for some reason...perl would be easier)
that parses a comma separated file, and then, for each line,
prints any two of many csv values.

.....to hard code the reading of two positional values,
you might do something like:

#/bin/bash

IFS=,
while read line
do
set $line
echo "$1 $6"
done

QUESTION:
how would you send the positions in as arguments?

echo "$$2 $$3" doesn't do what I hoped.
From: Janis Papanagnou on
sandy wrote:
> I want to write a bash script (for some reason...perl would be easier)
> that parses a comma separated file, and then, for each line,
> prints any two of many csv values.
>
> ....to hard code the reading of two positional values,
> you might do something like:
>
> #/bin/bash
>
> IFS=,
> while read line
> do
> set $line
> echo "$1 $6"
> done
>
> QUESTION:
> how would you send the positions in as arguments?
>
> echo "$$2 $$3" doesn't do what I hoped.

IFS=,
while read -r f1 f2 f3 f4 f5 f6 rest
do echo "$f1 $f6"
done

But mind that if your CSV fields may contain commata your approach
won't work as you'd expect.

Janis
From: Maxwell Lol on
sandy <rigamajig(a)borderline.org> writes:

> I want to write a bash script (for some reason...perl would be easier)
> that parses a comma separated file, and then, for each line,
> prints any two of many csv values.
>
> ....to hard code the reading of two positional values,
> you might do something like:
>
> #/bin/bash
>
> IFS=,
> while read line
> do
> set $line
> echo "$1 $6"
> done


#/bin/bash
arg1=${1?'Missing first argument'}
arg2=${2?'Missing second argument'}
IFS=,
while read line
do
set $line
eval echo \$$arg1 \$$arg2
done

Can fields contain commas in quotes?


From: pk on
sandy wrote:

> I want to write a bash script (for some reason...perl would be easier)
> that parses a comma separated file, and then, for each line,
> prints any two of many csv values.
>
> ....to hard code the reading of two positional values,
> you might do something like:
>
> #/bin/bash
>
> IFS=,
> while read line
> do
> set $line
> echo "$1 $6"
> done
>
> QUESTION:
> how would you send the positions in as arguments?
>
> echo "$$2 $$3" doesn't do what I hoped.

(strictly answering, ignoring everything else)

You can't do that, since you redefine the positional parameters with set.
You can do:

arg1=$2
arg2=$3

....
set $line
eval echo \""\$$arg1 \$$arg2"\"
....

with bash, you can also do

echo "${!arg1} ${!arg2}"
From: sandy on

> Can fields contain commas in quotes?

In the real world yes, of course, usually with double
quotes around the comma-containing field:

"123 Bluedoo Drive, Bozeman, MT, 59715"

With perl I read byte by byte, from left to right, setting a flag when
inside quote pairs, and then change those commas to an unprintable char.
Then I parse on the remaining commas (which did separate fields).
And then change the unprintable char back to a comma later on.
How do that in bash I have no idea.

Thanks for the help. I'll work with those ideas.