Shell: CSV to array

2019-08-23 07:03发布

I have two text files (converted from csv). The files (limits.txt and tbls.txt) has content such as below. The columns are comma separated.

sdafggggad57659asdvjh,8723,345
asdhfg878yeragjh,3456,234
iuhdsrg0987djhg,89787,876

I need to compare the first column of both the files to check if the 2nd and 3rd columns match or differ.

right now i have used the method mentioned below as suggested by @Andre Gelinas. BASH - How to extract data from a column in CSV file and put it in an array? My code looks like given below.

limit_t=( $(cut -d "," -f1 limits.txt))
limit_r=( $(cut -d "," -f2 limits.txt))
limit_w=( $(cut -d "," -f3 limits.txt))

tbls_t=( $(cut -d "," -f1 tbls.txt))
tbls_r=( $(cut -d "," -f2 tbls.txt))
tbls_w=( $(cut -d "," -f3 tbls.txt))

As you can see i have to declare 3 array variables per file to store three columns. I need to compare these arrays with each other to get my output. Is there a way that i can use just one multidimensional array variable per file so the code will be a little slimmer.

标签: arrays shell csv
1条回答
成全新的幸福
2楼-- · 2019-08-23 07:57

you could use -r option of read command:

#!/bin/bash
while IFS=',' read -r -a my_array; do
    echo ${my_array[0]} ${my_array[1]} ${my_array[2]}
done <<< $(cat limit.txt)
查看更多
登录 后发表回答