user1955215
user1955215

Reputation: 743

Joining two files using awk

File 1
---------+
|ID |
+---------+
|      15 |
|      45 |
|      18 |
|      76 |
|      29 |
|      10 |
|      40 |
+---------+
File 2:

| ID Name |
+---------+
| 12 abc  |
| 18 nop  |
| 15 ujh  |
| 30 jkl  |
| 15 lmn  |
| 18 tre  |
| 19 hgt  |
+---------+

Desired output:
+---------+
| ID Name |
+---------+
| 18 nop  |
| 15 ujh  |
| 15 lmn  |
| 18 tre  |
+---------

The Join cammand below is not giving the desired result (It should return all rows in File 2 where the value in the first column exists in the File1 table.

join -1 1 -2 1 File1.txt File2.txt

Please help.

Upvotes: 0

Views: 52

Answers (1)

Jef
Jef

Reputation: 1148

Well, since you ask specifically for an awk solution, here's one approach:

#!/bin/sh

awk 'BEGIN {
    while ((getline line < "File1.txt") > 0) {
        split(line, a)
        for (fld in a) {
            if (a[fld] ~ /^[0-9]*$/ ) {
                targets[a[fld]]=a[fld]
            }
        }
    }
} {
    if (NF == 4 && $2 ~ /^[0-9]*$/ ) {
        if ($2 in targets) {
            print $0
        }
    } else {
        print $0
    }
}' File2.txt

Although, I wonder like @Mark Setchell why you wouldn't approach getting this output from the database, if you have access to it.

Upvotes: 1

Related Questions