0

| で区切られたフラット ファイルがあります。フラットファイル内の情報から更新したい。1 番目と 2 番目のフィールドの情報を使用して 3 番目のフィールドに入力したいと考えています。最初のフィールドから、そのデータを使用して 3 番目のフィールドがないデータと比較するときに、最後の 2 つの数値を無視したいと考えています。2番目のフィールドと照合するときは、正確にしたいです。新しいフラット ファイルを作成したくありません。既存のファイルを更新したい。ファイルから最初の 2 つのフィールドを取り出す方法を調査しましたが、それが達成しようとしている目標に役立つかどうかはわかりません。これらすべてをまとめると、最初と 2 番目のフィールドをファイル内の他のフィールドと比較して、フラット ファイルの一部の行で欠落している可能性がある 3 番目のフィールドを取得します。

awk -F'|' -v OFS='|' '{sub(/[0-9 ]+$/,"",$1)}1 {print $1 "\t" $2}' tstfile

最初のフィールド|2 番目のフィールド|3 番目のフィールド

元の入力:

t1ttt01|/a1

t1ttt01|/b1

t1ttt01|/c1

t1ttt03|/a1|1

t1ttt03|/b1|1

t1ttt03|/c1|1

l1ttt03|/a1|3

l1ttt03|/b1|3

l1ttt03|/c1|3

何をすべきか:

t1ttt03|/a1|1 = t1ttt01|/a1

比較するときt1ttt|/a1| = t1ttt|/a1

したがって

t1ttt01|/a1になる t1ttt01|/a1|/1

出力を次のように表示したい:

t1ttt01|/a1|1

t1ttt01|/b1|1

t1ttt01|/c1|1

t1ttt03|/a1|1

t1ttt03|/b1|1

t1ttt03|/c1|1

l1ttt03|/a1|3

l1ttt03|/b1|3

l1ttt03|/c1|3
4

1 に答える 1

0

片道awk:

awk '

# set the input and output field separator to "|"

BEGIN{FS=OFS="|"}

# Do this action when number of fields on a line is 3 for first file only. The
# action is to strip the number portion from first field and store it as a key
# along with the second field. The value of this should be field 3

NR==FNR&&NF==3{sub(/[0-9]+$/,"",$1);a[$1$2]=$3;next} 

# For the second file if number of fields is 2, store the line in a variable
# called line. Validate if field 1 (without numbers) and 2 is present in
# our array. If so, print the line followed by "|" followed by value from array.

NF==2{line=$0;sub(/[0-9]+$/,"",$1);if($1$2 in a){print line OFS a[$1$2]};next}1
' file file

テスト:

$ cat file
t1ttt01|/a1
t1ttt01|/b1
t1ttt01|/c1
t1ttt03|/a1|1
t1ttt03|/b1|1
t1ttt03|/c1|1
l1ttt03|/a1|3
l1ttt03|/b1|3
l1ttt03|/c1|3
$ awk 'BEGIN{FS=OFS="|"}NR==FNR&&NF==3{sub(/[0-9]+$/,"",$1);a[$1$2]=$3;next}NF==2{line=$0;sub(/[0-9]+$/,"",$1);if($1$2 in a){print line OFS a[$1$2]};next}1' file file
t1ttt01|/a1|1
t1ttt01|/b1|1
t1ttt01|/c1|1
t1ttt03|/a1|1
t1ttt03|/b1|1
t1ttt03|/c1|1
l1ttt03|/a1|3
l1ttt03|/b1|3
l1ttt03|/c1|3
于 2013-07-24T15:48:10.683 に答える