条件を使用して隣接フィールドの空白を埋める

条件を使用して隣接フィールドの空白を埋める

同じ場合は、「隣接フィールドテキスト」または「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

おすすめ記事