Bash processing of csv file with unknown number of columns

只愿长相守 提交于 2021-02-19 05:22:04

问题


I am trying to learn some text processing using bash.

How to make a bash script to read and process CSV file with unknown number of columns with first row as column headers?

Example input:

column1,column2,...,columnn
value11,value12,...,value1n
value21,value22,...,value2n
...
valuem1,valuem2,...,valuemn

output:

column1: value11
column2: value12
...
columnn: value1n

column1: value21
column2: value22
...
columnn: value2n

...

column1: valuem1
column2: valuem2
...
columnn: valuemn

回答1:


One simple approach is to set IFS=, and use read -a to read into an array:

#!/bin/bash
IFS=','
read -a headers
while read -a line; do
    for i in "${!line[@]}"; do
        echo "${headers[i]}: ${line[i]}"
    done
done

What happens is that the first line is read into the one-dimensional array $line, being split according to the character in $IFS. Subsequent lines are read in the same way while there is input available, and the ! in "${!line[@]}" instructs bash to loop over array indices instead of array values.

This will not work if the data use any sort of escaping method to include comma literals.



来源:https://stackoverflow.com/questions/19484001/bash-processing-of-csv-file-with-unknown-number-of-columns

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!