问题
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