使用散列数据类型将csv导入redis

时间:2017-12-29 05:04:25

标签: csv ubuntu awk redis

awk -F, 'NR > 0{print "SET", "\"calc_"NR"\"", "\""$0"\"" }' files/calc.csv | unix2dos | redis-cli --pipe

我使用上面的命令将csv文件导入到带有字符串数据类型的redis数据库中。等等,

set cal_1 product,cost,quantity
set cal_2 t1,100,5

如何导入hash数据类型,字段名称为rowcount,key作为列标题,value作为awk中的列值。

HMSET calc:1 product "t1" cost 100 quantity 5
HMSET calc:2 product "t2" cost 500 quantity 4

输入文件示例:

product    cost    quantity
 t1         100      5
 t2         500      4
 t3         600      9

我可以从awk获得此结果吗? 对于csv文件中的每一行,

HMSET calc_'row no'第1行第1列值当前行第1列值第1行第2列值当前行第2列值第1行第3列值urrent行第3列值

所以对于上面的例子,

HMSET calc_1 product t1 cost 100 quantity 5
HMSET calc_2 product t2 cost 500 quantity 4
HMSET calc_3 product t3 cost 600 quantity 9

动态显示所有行?

1 个答案:

答案 0 :(得分:1)

您可以使用以下awk命令:

awk '{if(NR==1){col1=$1; col2=$2; col3=$3}else{product[NR]=$1;cost[NR]=$2;quantity[NR]=$3;tmp=NR}}END{printf "[("col1","col2","col3"),"; for(i=2; i<=tmp;i++){printf "("product[i]","cost[i]","quantity[i]")";}print "]";}' input_file.txt
输入文件上的

product    cost    quantity
 t1         100      5
 t2         500      4
 t3         600      9

它提供以下输出:

[(product,cost,quantity),(t1,100,5)(t2,500,4)(t3,600,9)]

enter image description here

awk命令:

# gawk profile, created Fri Dec 29 15:12:39 2017

# Rule(s)

{
        if (NR == 1) { # 1
                col1 = $1
                col2 = $2
                col3 = $3
        } else {
                product[NR] = $1
                cost[NR] = $2
                quantity[NR] = $3
                tmp = NR
        }
}

# END rule(s)

END {
        printf "[(" col1 "," col2 "," col3 "),"
        for (i = 2; i <= tmp; i++) {
                printf "(" product[i] "," cost[i] "," quantity[i] ")"
        }
        print "]"
}