Parsing CSV


#!/bin/bash
# Purpose: Demonstrate parsing a simple CVS, when the order is predictable
# Author:
# ------------------------------------------
INPUT=$1

# If there was no file or the file doesn't exist, exit.
[ -z "$INPUT" -o ! -f "$INPUT" ] && { echo "Input missing or file $INPUT not found"; exit 99; }    

# Read one line at a time from the input file
IFS=","
while read ONE TWO THREE; do

    echo "  One: $ONE"
    echo "  Two: $TWO"
    echo "Three: $THREE"
    echo "__________________________"

done<$INPUT


#!/bin/bash
# Purpose: Demonstrate parsing a simple CVS when you must check the values more carefully
# Author:
# ------------------------------------------
INPUT=$1

# If there was no file or the file doesn't exist, exit.
[ -z "$INPUT" -o ! -f "$INPUT" ] && { echo "Input missing or file $INPUT not found"; exit 99; }    

# Read one line at a time from the input file
while read LINE; do

    # Change to "," as a deliminator to parse the line
    IFS="," read ONE TWO THREE <<< $LINE

    # Alternately, run through a loop
    IFS=","
    for X in $LINE;do echo $X;done
    echo "__________________________"

done<$INPUT


#!/bin/bash
# Purpose:
Demonstrate parsing a simple CVS using an array
# Author:
# ------------------------------------------
INPUT=$1
LINE=""
LINES=()

# If there was no file or the file doesn't exist, exit.
[ -z "$INPUT" -o ! -f "$INPUT" ] && { echo "Input missing or file $INPUT not found"; exit 99; }    

while read LINE; do

    LINES+=("${LINE}")

done<$INPUT

for LINE in "${LINES[@]}"; do

    IFS="," read ONE TWO THREE <<< $LINE
    # Do Something with ONE TWO THREE fields here

done






Comments