用条件填充相邻字段的空白

用条件填充相邻字段的空白

如果相同或“X”,我想用“相邻字段文本”填充(按行)空白。请建议 ( AWK/ sed) 解决方案。 (附加要求:计算时空字段的距离很重要,即使用标题记录时,空字段的距离应< 100)。否则,即使相邻字段匹配,也填充“X”。

Example of blank fields filled with "X" even after matching: Line0 $612-$822. 

输入(制表符分隔)

ID  577 592 598 600 612 650 700 822 825 830 840 870
Line0   A           A                   A           A
Line1   B           B                   NA          B
Line2   B           A                   A           A


异常空字段的解释

Exceptional intervals are Columns ID-600 to ID-822 because the distance is greater than 100

预期产出

ID  577 592 598 600 612 650 700 822 825 830 840 870
Line0   A   A   A   A   X   X   X   X   A   A   A   A
Line1   B   B   B   B   X   X   X   X   NA  X   X   B
Line2   B   X   X   A   X   X   X   X   A   A   A   A


答案1

不确定我是否正确理解了您的请求,但是怎么样

awk -F"\t" '
NR > 1  {i = 2
         while (i<=NF)  {if (!$i)       {while (!$(++i)) ;
                                         for (j=LAST+1; j<i; j++) $j = ($LAST == $i)?$LAST:"X"
                                        }
                         LAST = i++
                        }
        }
1
' OFS="\t" file

ID      s577    s592    s598    s600    s612    s650    s700    s822    s825    s830    s840    s870
line0   A       A       A       A       A       A       A       A       A       A       A       A
line1   B       B       B       B       X       X       X       X       NA      X       X       B
line2   B       X       X       A       A       A       A       A       A       A       A       A

根据要求提供带注释的版本:

awk -F"\t" '
NR > 1  {i = 2                                                  # Don't work on the header line
         while (i<=NF)  {if (!$i)       {while (!$(++i)) ;      # check every field if empty and
                                                                # increment i while seeing empty
                                                                # fields; i now holds next non-
                                                                # empty field 
                                         for (j=LAST+1; j<i; j++) $j = ($LAST == $i)?$LAST:"X"
                                                                # fill the empty fields with "X"
                                                                # or last non-empty field's value
                                                                # depending on actual and last
                                                                # fields' values being equal or not
                                        }
                         LAST = i++                             # retain last non-empty field
                        }
        }
1                                                               # default action: print
' OFS="\t" file

相关内容