[英]Checking column values are in the same order awk/bash
I have an input file: 我有一个输入文件:
A 23
A 45
A 32
A 61
A 78
B 23
B 45
B 32
B 61
B 78
C 23
**C 32
C 45**
C 61
C 78
The first column specifies a group, and the second column specifies some values for that group. 第一列指定一个组,第二列指定该组的一些值。
I want to check if the order of values for each group is the same. 我想检查每个组的值顺序是否相同。
For example, the values are 23,45,32,61,78 for group A. The values are in the same order for group B. But in group C there is a violation of the order (in bold), therefore the output should simply be "false". 例如,组A的值是23、45、32、61、78。组B的值是相同的顺序。但是在组C中,该顺序是违反的(粗体),因此输出应为简单地是“假”。
If group C, the order of values is followed as well, the output would be "true". 如果是C组,则也要遵循值的顺序,输出将为“ true”。
Note that the groups in the first column are all unique, there is no repeated group. 请注意,第一列中的组都是唯一的,没有重复的组。
!f { a[++i] = $2 } # save first sequence
NR>1 && $1!=p { f=1; i=1 } # set flag and reset index on new sequence
{ p=$1 } # save value of first column
f && a[i++]!=$2 { m=1; exit } # if number not in sequence, set m and exit early
END { print m?"false":"true" } # print false or true, depending on m
Run it like awk -f script.awk file
像
awk -f script.awk file
一样运行
This awk
should work: 这个
awk
应该工作:
awk '$1 != p {
if (!grp1 && grp)
grp1 = grp;
if (grp != grp1) {
print p " - false";
done = 1;
exit
};
grp = "";
p = $1
}
{
grp = grp ":" $2
}
END {
if (!done && grp != grp1)
print p " - false"
}' file
It prints: 它打印:
C - false
Another solution: 另一个解决方案:
NR == 1 {
initial = $1
returnVal = ""
}
{
if (initial == $1) {
array[++i] = $2
} else {
if (anchor != $1)
ix = 0
anchor = $1
if (array[++ix] != $2) {
returnVal = 1
}
}
}
END {
print (returnVal) ? "false" : "true" ;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.