Понимание двух файловой обработки в awk - PullRequest
0 голосов
/ 22 февраля 2019

Я пытаюсь понять, как работает обработка двух файлов.Итак, здесь создан пример.file1.txt

zzz pq Fruit Apple 10
zzz rs Fruit Car 50
zzz tu Study Book 60

file2.txt

aa bb Book 100
cc dd  Car 200
hj kl XYZ 500
ee ff Apple 300
ff gh ABC 400

Я хочу сравнить 4-й столбец file1 с 3-м столбцом file2, если он совпадает, вывести 3-й, 4-й, 5-й столбец file1, за которым следуют 3-й, 4-й столбец file2 с суммой 5-го столбца файла1 и 4-го столбца файла2.

Ожидаемый результат:

Fruit Apple 10 300 310
Fruit Car 50 200 250
Study Book 60 100 160

Вот чтоЯ попытался:

awk ' FNR==NR{ a[$4]=$5;next} ( $3 in a){ print $3, a[$4],$4}' file1.txt file2.txt

Вывод кода;

Book  100
Car  200
Apple  300

У меня возникла проблема при печати столбца file1 и способе хранения other column of file1 in array a.Пожалуйста, ведите меня.

1 Ответ

0 голосов
/ 22 февраля 2019

Не могли бы вы попробовать следующее.

awk 'FNR==NR{a[$4]=$3 OFS $4 OFS $5;b[$4]=$NF;next} ($3 in a){print a[$3],$NF,b[$3]+$NF}' file1.txt  file2.txt

Вывод будет следующим.

Study Book 60 100 160
Fruit Car 50 200 250
Fruit Apple 10 300 310

Объяснение: Добавление объяснения длякод выше.

awk '                              ##Starting awk program here.
FNR==NR{                           ##Checking condition FNR==NR which will be TRUE when first Input_file named file1.txt is being read.
  a[$4]=$3 OFS $4 OFS $5           ##Creating an array named a whose index is $4 and value is 3rd, 4th and 5th fields along with spaces(By default OFS value will be space for awk).
  b[$4]=$NF                        ##Creating an array named b whose index is $4 and value if $NF(last field of current line).
  next                             ##next keyword will skip all further lines from here.
}
($3 in a){                         ##Checking if 3rd field of current line(from file2.txt) is present in array a then do following.
  print a[$3],$NF,b[$3]+$NF        ##Printing array a whose index is $3, last column value of current line and then SUM of array b with index $3 and last column value here.
}
' file1.txt  file2.txt             ##Mentioning Input_file names file1.txt and file2.txt
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...