在不同的列中输出每个循环的结果 [英] Output the result of each loop in different columns

查看:51
本文介绍了在不同的列中输出每个循环的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

price.txt文件有两列:(名称和值)

price.txt file has two columns: (name and value)

Mary 134
Lucy 56
Jack 88

range.txt文件具有三列:(水果,最小值和最大值)

range.txt file has three columns: (fruit and min_value and max_value)

apple 57 136
banana 62 258
orange 88 99
blueberry 98 121

我的目的是测试price.txt文件中的值是否在range.txt中的min_value和max_value之间.如果是,则输出1,否则,输出"x".

My aim is to test whether the value in price.txt file is between the min_value and max_value in range.txt. If yes, putout 1, If not, output "x".

我尝试过:

awk 'FNR == NR { name=$1; price[name]=$2; next} { 
     for (name in price) { 
         if ($2<=price[name] && $3>=price[name]) {print 1} else {print "x"}
     } 
 }' price.txt range.txt

但是我的结果全都放在一栏中,如下所示:

But my results are all in one column, just like follows:

1
1
x
x
x
x
x
x
1
1
1
x

实际上,我希望我的结果像这样:(每个名称都有一列)

Actually, I want my result to be like: (Each name has one column)

1 x 1
1 x 1
x x 1
x x x

因为我需要使用paste一起将输出文件和range.txt文件添加在一起.最终结果应为:

Because I need to use paste to add the output file and range.txt file together. The final result should be like:

apple 57 136 1 x 1
banana 62 258 1 x 1
orange 88 99 x x 1
blueberry 98 121 x x x

那么,如何获得不同列中每个循环的结果?而且是否有根据我当前的代码在没有paste的情况下输出最终结果的方法?谢谢.

So, how can I get the result of each loop in different columns? And is there anyway to output the final result without paste based on my current code? Thank you.

推荐答案

这是基于您提供的内容

# load prices by index to maintain read order
FNR == NR {
    price[names++]=$2
    next
}
# save max index to avoid using non-standard length(array)
END {
    names=NR
}
{
 l = $1 " " $2 " " $3
 for (i=0; i < names; i++) {
     if ($2 <= price[i] && $3 >= price[i]) {
             l = l " 1"
     } else {
             l = l " x"
    }
 }
 print l
}

并生成输出,

apple 57 136 1 x 1
banana 62 258 1 x 1
orange 88 99 x x 1
blueberry 98 121 x x x

但是,您没有分数的人名(匿名结果)-也许是故意的?

However, you don't have the person name for the score (anonymous results) - maybe that's intentional?

此处的更改是显式索引第一个块中填充的数组以保持顺序.

The change here is to explicitly index array populated in first block to maintain order.

这篇关于在不同的列中输出每个循环的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆