Grep and replace with found string

Hi,

I need to find all rows in 1st col of one file in another file (first occurrence) and replace the 1st col of first file with the grep result (the entire line). For example search AA from file 1 in file 2 and replace in file 1 by entire line found.

File1

AA BB CC DD
BB AA CC DD

File2

bbbbbbAADDDDCDCDKLK
bbbbbbAADDBDCDCDKLK
bbbbbbBBDCDCDKLK

output

bbbbbbAADDDDCDCDKLK BB CC DD
bbbbbbBBDCDCDKLK AA CC DD
awk 'NR==FNR{A[$1];next}{for(k in A) if(k~$1) $1=k}1' file2 file1
1 Like

The for(k in A) in Yoda's script will search entries in A in random order. To pick the 1st line in File2 that contains a match, you could try something like:

awk '
FNR == NR {
        f[++c] = $0
        next
}
{       for(i = 1; i <= c; i++)
                if(index(f, $1)) {
                        $1 = f
                        break
                }
        print
}' File2 File1
1 Like