您好,感谢您的阅读。这似乎很简单,我只需要一个for循环。
我有一个巨大的数据文件,
212
265
2321
12
183
等等等
我需要做的是,如果该值小于上一行,则在每行的末尾附加“>”,如果该值小于上一行,则在其后加上“ <” 1f。所以我想要的输出是
212 <
265 >
2321 >
12 <
183 >
此代码
awk '{if ($1<prev); print ("<"); prev=$0}' input > output
仅对所有行给出<。
如何以awk或任何其他bash的方式完成此任务?
答案 0 :(得分:4)
$ awk '{print $0, ($0 > prev ? ">" : "<"); prev=$0}' file
212 >
265 >
2321 >
12 <
183 >
或者也许这样可以更好地满足您的要求,以处理文件中的第一个值:
$ awk '{print $0, ((NR > 1) && ($0 > prev) ? ">" : "<"); prev=$0}' file
212 <
265 >
2321 >
12 <
183 >
写了为什么您的代码不起作用,您写道:
{if ($1<prev); print ("<"); prev=$0}
这是:
{if ($1<prev); # Test $1 vs prev but then do nothing based on the result of the
# comparison since the semi-colon terminates the conditional block
print ("<"); # Always print a "<" symbol for every input line
prev=$0} # Set prev to the current lines value