Awk - Valores de correspondência entre dois arquivos
Tenho dois arquivos que estou tentando comparar e criar um arquivo final.txt com dados existentes de ambos os arquivos.
Arquivo1 - coluna 1 e Arquivo2 - colunas 2 contêm o valor que preciso corresponder entre os dois arquivos.
Então, essencialmente, estou tentando -> pegar a coluna1 do Arquivo1, se houver uma correspondência na coluna2 do arquivo2, então escrever Arquivo1Coluna1, Arquivo1Coluna2 e Arquivo2Coluna1 em um novo arquivo chamado final.txt.
EXEMPLO
Arquivo 1
1000,Brian
1010,Jason
400,Nick
Arquivo 2
3044 "1000"
4466 "400"
1206 "1010"
arquivo de saída para parecer
1000,Brian,3044
1010,Jason,1206
400,Nick,4466
meu código de teste não mostra nenhum resultado
awk -F"[,]" 'NR==FNR{a[$1]=$1","$2;next} ($2 in a){print a[$2]","$1}' file1.txt file2.txt
Eu acredito que deveria ser capaz de fazer isso com awk, mas por alguma razão estou realmente lutando com este. Qualquer ajuda seria muito apreciada.
Obrigado
Respostas
Você poderia tentar seguir, escrito e testado com seus exemplos mostrados no GNU awk
.
awk '
FNR==NR{
gsub(/"/,"",$2) arr[$2]=$1 next } FNR==1{ FS="," OFS="," $0=$0 } ($1 in arr){
print $0,arr[$1]
}
' Input_file2 Input_file1
Explicação: Adicionando explicação detalhada acima.
awk ' ##Starting awk program from here.
FNR==NR{ ##Checking condition FNR==NR which will be TRUE when Input_file1 is being read.
gsub(/"/,"",$2) ##globally substituting " in 2nd field with NULL. arr[$2]=$1 ##Creating array arr with index of 2nd field and value of 1st field. next ##next will skip all further statements from here. } FNR==1{ ##Checking condition if this is first line of Input_file1. FS="," ##Setting FS as comma here. OFS="," ##Setting OFS as comma here. $0=$0 ##Reassigning current line to itself so that field separator values will be implemented to current line. } ($1 in arr){ ##Checking condition if 1st field is present in arr then do following.
print $0,arr[$1] ##Printing current line and value of array arr.
}
' file2 file1 ##Mentioning Input_file names here.
Você não incluiu linhas que não correspondam entre os 2 arquivos de entrada em sua entrada / saída de amostra, portanto, isso pode ou não fazer o que você deseja nesses casos:
$ cat tst.awk BEGIN { FS="[[:space:]\",]+"; OFS="," } NR==FNR { map[$2] = $1 next } { print $0, map[$1] }
$ awk -f tst.awk file2 file1
1000,Brian,3044
1010,Jason,1206
400,Nick,4466