Awk - Valori di corrispondenza tra due file
Ho due file che sto cercando di confrontare e creare un file final.txt con i dati che esistono da entrambi i file.
File1 - colonna 1 e File2 - colonne 2 contengono il valore che devo abbinare tra i due file.
Quindi, essenzialmente, sto cercando di -> prendere la colonna1 da File1, se c'è una corrispondenza nella colonna2 di file2, quindi scrivere File1Colonna1, File1Colonna2 e File2Colonna1 in un nuovo file chiamato final.txt.
ESEMPIO
File 1
1000,Brian
1010,Jason
400,Nick
File 2
3044 "1000"
4466 "400"
1206 "1010"
file di output per assomigliare
1000,Brian,3044
1010,Jason,1206
400,Nick,4466
il mio codice di prova non mostra alcun risultato
awk -F"[,]" 'NR==FNR{a[$1]=$1","$2;next} ($2 in a){print a[$2]","$1}' file1.txt file2.txt
Credo che dovrei essere in grado di farlo con awk, ma per qualche motivo sto davvero lottando con questo. Qualsiasi aiuto sarebbe molto apprezzato.
Grazie
Risposte
Potresti per favore provare a seguire, scritto e testato con gli esempi mostrati in 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
Spiegazione: aggiunta di una spiegazione dettagliata per quanto sopra.
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.
Non hai incluso alcuna riga che non corrisponda tra i 2 file di input nel tuo input / output di esempio, quindi questo può o non può fare quello che vuoi per quei casi:
$ 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