Shell脚本-循环浏览csv文件中多列中的值 [英] Shell script - loop through values in multiple columns of a csv file
问题描述
我正在处理一个包含两列的巨大CSV文件(filename.csv
).从第1列中,我想读取当前行并将其与上一行的值进行比较.如果它是greater
或equal
,请继续比较,如果当前单元格的值比上一行smaller
-那么我想跳到第二列,并在(第二列).接下来,我想将第1列中获得的值larger value
除以第2列相同单元格中的值.例如,在下表中:根据我的要求,我们将获得的较小值是327(因为327小于先前的值340)-然后我们取500(这是第二列上的对应单元格值).最后,我们将340除以500,得到的值是0.68.将值打印到控制台后,我的bash脚本应立即退出.
I am working with a huge CSV file (filename.csv
) that contains two columns. From column 1, I wanted to read current row and compare it with the value of the previous row. If it is greater
OR equal
, continue comparing and if the value of the current cell is smaller
than the previous row - then i wanted to jump to the second column and take the value in the current row (of the second column). Next I wanted to divided the value larger value
we got in column 1 by the value in the same cell of column two. For example in the following table: the smaller value we will get depending on my requirement is 327 (because 327 is smaller than the previous value 340) - and then we take 500 (which is the corresponding cell value on column two). Finally we divide 340 by 500 and get the value 0.68. My bash script should exit right after we print the value to the console.
338 800
338 550
339 670
340 600
327 500
301 430
299 350
284 339
284 338
283 335
283 330
283 310
282 310
282 300
282 300
283 290
在以下脚本中,它仅适用于第1列,但我想根据我上面提到的标准将其扩展为两列.
In the following script, it works only for column 1 but i want to extend it for two columns based on my criteria i mentioned above.
awk '$1<p{
val=$1/p
if(val>=0.8 && val<=0.9)
{
print "value is:" $1/p
print "A"
}
else if(val==0.8)
{
print "B"
}
else if(val>=0.6 && val <=0.7)
{
print "C"
}
else if(val==0.5)
{
print "E"
}
else
{
print "D"
}
exit
}
{
p=$1
}' filetest.csv
我们如何遍历两列中的值并执行控制语句?
How can we loop through the values in two columns and perform control statement?
PS:我的if-else语句的条件是(如果值> = 0.8并且< = 0.9,则打印A,否则,如果值)是> = 0.7并且< = 0.8,则打印B,如果值>> 0.5且< = 0.7打印C,否则打印D).
PS: the criteria for my if-else statement is (if the value is >=0.8 and <=0.9, print A, else if the value) is >=0.7 and <=0.8, print B, if the value is >=0.5 and <=0.7 print C otherwise print D).
推荐答案
您的第一个期望值0.654
大于0.65
(最接近的第三个条件),这就是为什么它不适合您的任何一个条件.
Your first expected value 0.654
is bigger than 0.65
(the 3rd condition as the closest one), that's why it doesn't fit any of your conditions.
如下所示扩展脚本:
awk '$1<p{
val=$1/$2 # to divide the first column value on the second column value
if(val>=0.85 && val<=0.9)
{
print "value is:" $1/p
print "A"
}
else if(val==0.8)
{
print "B"
}
else if(val>=0.5 && val <=0.7)
{
print "C"
}
else if(val==0.5)
{
print "E"
}
else
{
print "D"
}
exit
}
{
p=$1
}' filetest.csv
输出:
C
我修改过的关键行是:
The crucial line I've modified is:
val=$1/$2 # to divide the first column value on the second column value
这篇关于Shell脚本-循环浏览csv文件中多列中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!