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

问题描述 投票:2回答:1
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

如何导入哈希数据类型,字段名称为行计数,键为列标题,值为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

动态的所有行?

csv ubuntu awk redis
1个回答
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 "]"
}
© www.soinside.com 2019 - 2024. All rights reserved.