Reputation: 625
Would like to know how to handle if the two files are having different de-limiters:
Like to compare second field - substr($2,3,2)from F11.txt , de-limited by "|" and first field from F22.txt, de-limited by "," then Print match cases only from both the files:
Inputs:
F11.txt
a|mm10|zzz
b|mm20|zzz
c|mm50|zzz
F22.txt
10,yyy
20,yyy
30,yyy
40,yyy
Have tried like below and struck to proceed further:
awk ' BEGIN {FS = OFS = ","} FNR==NR {a[$1] = $0; next} (substr($2,3,2) in a) {print $0, a[$2]}' f22.txt f11.txt
Desired Output:
a,10,zzz,10,yyy
b,20,zzz,20,yyy
Upvotes: 0
Views: 213
Reputation: 203995
THE way to do this is to just change the delimiter between files:
awk '...' FS="," file1 FS="|" file2
e.g.
$ awk -v OFS="," '
NR==FNR { a[$1]=$2; next }
{ $2=substr($2,3,2); if ($2 in a) print $0, $2, a[$2] }
' FS="," f22.txt FS="|" f11.txt
a,10,zzz,10,yyy
b,20,zzz,20,yyy
Upvotes: 1
Reputation: 85845
Modify with sed
then use join
:
sed 's/|/,/g;s/[a-z]*//2' file1|join -1 2 -2 1 -t, -o 1.1,1.2,1.3,2.1,2.2 - file2
a,10,zzz,10,yyy
b,20,zzz,20,yyy
Upvotes: 0
Reputation: 290025
It is a bit tricky... but it works :)
awk -v FS="|" -v OFS=","
'BEGIN{s=""}
FNR==NR{b=substr($2,3,2)
$2=b
for (i=1; i<=NF; i++) s=s""$i""OFS
a[b]=s
s=""
next}
($1 in a) {print a[$1] $0}' f1 FS="," OFS= f2
It makes use of different FS and OFS for each file, so that the processing is done properly. Then, it is a matter of storing each line of f1 on the array a[substr($2,3,2)]
, so that we can detect if that value is in the first field of the second file or not.
$ awk -v FS="|" -v OFS="," 'BEGIN{s=""} FNR==NR{b=substr($2,3,2); $2=b; for (i=1; i<=NF; i++) s=s""$i""OFS; a[b]=s; s=""; next} ($1 in a) {print a[$1], $0}' f1 FS="," OFS= f2
a,10,zzz,10,yyy
b,20,zzz,20,yyy
Upvotes: 0