bash read csv file store value into a variable

时间:2019-03-17 22:36:56

标签: bash

I would like to read csv using Bash and store each value into a variable for further processing. my csv file looks like below, all the values are unique.

> val1-row1,val2-row1,val3-row1,val4-row1....valn-row1
> val1-row2,val2-row2,val3-row2,val4-row2....valn-row2

My code below

 while IFS=, read eachvalue; 
    do
   if [ "$eachvalue" = "something" ]
   then
    echo "do something"
   else
    echo "do something else"
   fi
    done < allvalues.csv

I am unable to read each value and do if condition for each value in csv file. Thanks for your help.

1 个答案:

答案 0 :(得分:1)

IFS=,仅在使用read -a读入数组,或者在要读取的每一列中传递一个变量名时才有用。下面,我们做前者:

#!/usr/bin/env bash
#              ^^^^ -- NOT /bin/sh

row_idx=0
while IFS=, read -ra values; do
  for col_idx in "${!values[@]}"; do value=${values[$col_idx]}
    if [ "$value" = something ]; then
      echo "something found on row $row_idx, column $col_idx"
    fi
  done
  (( ++row_idx ))
done

看到此代码在https://ideone.com/JN1pK3处运行,输出(将something插入到输入的第二行中,在末尾附近):something found on row 1, column 4(请记住,两行和列的索引为零)。