How do I read, split and derive from CSV using bash script? - Unix
This is a discussion on How do I read, split and derive from CSV using bash script? - Unix ; I have a CSV file that I need to obtain values from... have absolutely
NO idea how to do it at all, except for:
stuff=`cat ./directory_setup/directory_setup.csv`
From there I'm lost. I need to then do the PHP equivalent of
fgetscsv() ...
-
How do I read, split and derive from CSV using bash script?
I have a CSV file that I need to obtain values from... have absolutely
NO idea how to do it at all, except for:
stuff=`cat ./directory_setup/directory_setup.csv`
From there I'm lost. I need to then do the PHP equivalent of
fgetscsv() to get a specific column field from the parsed CSV file, or
even the TCL equivalent of split/list/split to parse it and retrieve
it.
How is it done though in Bash? I am ultimately trying to dynamically
obtain the document root which is entered as a value in a CSV file
(have no other known way of ever knowing that in the scope of the
portable/scalable script I'm writing)
Thanx
Phil
-
Re: How do I read, split and derive from CSV using bash script?
On Sun, 25 Jan 2004 at 03:01 GMT, Phil Powell wrote:
> I have a CSV file that I need to obtain values from... have absolutely
> NO idea how to do it at all, except for:
>
> stuff=`cat ./directory_setup/directory_setup.csv`
>
> From there I'm lost. I need to then do the PHP equivalent of
> fgetscsv() to get a specific column field from the parsed CSV file, or
> even the TCL equivalent of split/list/split to parse it and retrieve
> it.
>
> How is it done though in Bash? I am ultimately trying to dynamically
> obtain the document root which is entered as a value in a CSV file
> (have no other known way of ever knowing that in the scope of the
> portable/scalable script I'm writing)
This function splits a CSV line into its components, and stores
them in an array called values:
csv_split() { ## USAGE: csv_split CSV_RECORD
local record=${1%"${CR}"}
local right
local vnum=0
unset values
while [ -n "$record" ]
do
case $record in
\"*) right=${record#*\",}
value=${record%%\",*}
values[$vnum]=${value#\"}
;;
*) values[$vnum]=${record%%,*}
right=${record#*,}
;;
esac
case $record in
*,*) record=${right} ;;
*) record=${record#\"}
values[$vnum]=${record%\"}
break;;
esac
vnum=$(( $vnum + 1 ))
done
}
N=3
CR=$'\r'
while IFS= read -r line
do
csv_split "$line"
printf "%s\n" "${values[N]}" ## print field N (numbered from 0)
done < ./directory_setup/directory_setup.csv
--
Chris F.A. Johnson http://cfaj.freeshell.org
================================================== =================
My code (if any) in this post is copyright 2004, Chris F.A. Johnson
and may be copied under the terms of the GNU General Public License