0

This question already has an answer here:

I have two files:

file 1:

a,txt1,v1
b,txt2,v2
c,txt3,v1
d,txt4,v2

file2:

a,txt5,v2
b,txt6,v1
xc,txt7,v1
xd,txt8,v2

I want to refine the files. I only need the lines where the 1st column in file1 has match in file2.

The new file1 should contain:

a,txt1,v1
b,txt2,v2

Similarly, file2 should be refined to contain only lines where there is a match in the 1st column with file1. So file2 should be:

a,txt5,v2
b,txt6,v1

marked as duplicate by slm Jul 14 '18 at 2:53

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

0

Here's a Bash script that should do what you want:

#!/bin/bash
# match.sh

file1="$1"
file2="$2"

while read line; do
    column="$(echo "${line}" | cut -d, -f1)"
    if grep -Pq "^${column}," "${file2}"; then
        echo "${line}"
    fi
done < "${file1}"

You would run it like this:

user@host:~$ bash match.sh file1 file2
a,txt1,v1
b,txt2,v2

user@host:~$ bash match.sh file2 file1

a,txt5,v2
b,txt6,v1

And here's a Python script that does essentially the same thing:

#!/usr/bin/env python
"""match.py"""

import sys
import csv

with open(sys.argv[1], 'r') as file1:
    reader1 = csv.reader(file1)
    for row1 in reader1:
        with open(sys.argv[2], 'r') as file2:
            reader2 = csv.reader(file2)
            for row2 in reader2:
                if row1[0] == row2[0]:
                    print(','.join(row1))
                    break

Not the answer you're looking for? Browse other questions tagged or ask your own question.