![最初の列から一致する行を抽出しますか? [コピー]](https://linux33.com/image/136925/%E6%9C%80%E5%88%9D%E3%81%AE%E5%88%97%E3%81%8B%E3%82%89%E4%B8%80%E8%87%B4%E3%81%99%E3%82%8B%E8%A1%8C%E3%82%92%E6%8A%BD%E5%87%BA%E3%81%97%E3%81%BE%E3%81%99%E3%81%8B%EF%BC%9F%20%5B%E3%82%B3%E3%83%94%E3%83%BC%5D.png)
2つのファイルがあります。
ファイル1:
a,txt1,v1
b,txt2,v2
c,txt3,v1
d,txt4,v2
ファイル2:
a,txt5,v2
b,txt6,v1
xc,txt7,v1
xd,txt8,v2
文書を完成させたいです。最初の列にfile1
一致する行のみが必要ですfile2
。
新しい file1 には以下を含める必要があります。
a,txt1,v1
b,txt2,v2
繰り返しますが、file2
最初の列に一致する行のみを含めるようにオーバーライドする必要がありますfile1
。したがって、file2は次のようになります。
a,txt5,v2
b,txt6,v1
答え1
目的のタスクを実行するBashスクリプトは次のとおりです。
#!/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}"
次のように実行できます。
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
デフォルトでは、同じことを行うPythonスクリプトは次のとおりです。
#!/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