【发布时间】:2017-05-17 20:32:25
【问题描述】:
我有一个包含以下数据的文件-
输入-
A B C D E F
A B B B B B
C A C D E F
A B D E F A
A A A A A F
A B C B B B
如果从第 2 行开始的任何其他行与第 1 行具有相同的字母,则应将它们更改为 1。基本上,我试图找出任何行与第一行的相似程度。
期望的输出-
1 1 1 1 1 1
1 1 B B B B
C A 1 1 1 1
1 1 D E F A
1 A A A A 1
1 1 1 B B B
第一行全为 1,因为它与自身相同(显然)。在第二行中,第一列和第二列与第一行 (A B) 相同,因此它们变为 1 1。其他行以此类推。
我已经编写了以下代码来进行这种转换-
for seq in {1..1} ; #Iterate over the rows (in this case just row 1)
do
for position in {1..6} ; #Iterate over the columns
do
#Define the letter in the first row with which I'm comparing the rest of the rows
aa=$(awk -v pos=$position -v line=$seq 'NR == line {print $pos}' f)
#If it matches, gsub it to 1
awk -v var=$aa -v pos=$position '{gsub (var, "1", $pos)} 1' f > temp
#Save this intermediate file and now act on this
mv temp f
done
done
您可以想象,这真的很慢,因为嵌套循环很昂贵。我的真实数据是一个 60x10000 的矩阵,这个程序在上面运行大约需要 2 个小时。
我希望您能帮助我摆脱内部循环,以便我可以一步完成所有 6 个 gsub。也许将它们放在自己的数组中?我的awk 技能还不是很好。
【问题讨论】: