Unix merges into several fields into two files

I have two files

cat test1.txt

1|2|3|4 2|3|4|4 3|4|5|5 

cat test2.txt

 1|2|4|5 2|3|5|6 3|5|7|7 

My conclusion should be

 1|2|3|4|4|5 2|3|4|4|5|6 

This is like combining two files into fields 1 and 2 and getting the values ​​1,2,3,4 from files 1 and 3.4 from file 2.

Please help me with this?

+4
source share
5 answers
 awk -F\| 'NR == FNR { f2[$1, $2] = $3 OFS $4 next } ($1, $2) in f2 { print $0, f2[$1, $2] }' OFS=\| test2.txt test1.txt 
+5
source

Try to do it in perl

 paste -d '|' file1.txt file2.txt | perl -F'\|' -lane ' print join "|", @F[0..3,6,7] if $F[0] eq $F[4] and $F[1] eq $F[5] ' 

And in sh :

 #!/bin/sh paste -d '|' test1.txt test2.txt | while IFS='|' read a1 a2 a3 a4 a5 a6 a7 a8; do if [ $a1 -eq $a5 -a $a2 -eq $a6 ]; then echo "$a1|$a2|$a3|$a4|$a7|$a8" fi done 

OUTPUT

 1|2|3|4|4|5 2|3|4|4|5|6 
+2
source

Hmm, this works for your example:

  sed 's/|/+/' t1.txt>$$.tmp;sed 's/|/+/' t2.txt|join -t \| -j 1 $$.tmp -|sed 's/+/|/';rm $$.tmp 
+2
source

This also works:

 $ sed 's/|/\t/2' 1.txt > 1_1.txt; sed 's/|/\t/2' 2.txt > 2_1.txt; $ join -j1 1_1.txt 2_1.txt | tr ' ' '|' $ rm 1_1.txt 2_1.txt 

Single line file without creating a temporary file (thanks to @dbaupp):

 $ join -j1 <(sed 's/|/\t/2' 1.txt) <(sed 's/|/\t/2' 2.txt) | tr ' ' '|' 
+2
source

Another solution:

 awk -F "|" '{getline a < "file1"}NR==1{print a, $3, $4 "\n"}NR==3{print a, $3, $4}' OFS="|" file2 

Result:

 $ awk -F "|" '{getline a < "file1"}NR==1{print a, $3, $4 "\n"}NR==3{print a, $3, $4}' OFS="|" file2 1|2|3|4|4|5 2|3|4|4|5|6 
0
source

Source: https://habr.com/ru/post/1444656/


All Articles