![](/img/trans.png)
[英]Fuse values from first column, when the values from second column is the same in different files in awk or bash by using awk or bash
[英]Checking column values are in the same order awk/bash
我有一個輸入文件:
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
第一列指定一個組,第二列指定該組的一些值。
我想檢查每個組的值順序是否相同。
例如,組A的值是23、45、32、61、78。組B的值是相同的順序。但是在組C中,該順序是違反的(粗體),因此輸出應為簡單地是“假”。
如果是C組,則也要遵循值的順序,輸出將為“ true”。
請注意,第一列中的組都是唯一的,沒有重復的組。
!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
像awk -f script.awk file
一樣運行
這個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
它打印:
C - false
另一個解決方案:
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.