[英]BASH comm command, but for multiple columns
我正在尋找類似於 bash 命令 comm 的東西,我可以用它來選擇我的 2 個文件獨有的條目和它們共有的條目。 當我每個文件只有一列時,Comm 工作得很好,例如。
comm -13 FILE1.txt FILE2.txt > Entries_only_in_file1.txt
但現在我有多列信息希望保留。 我想選擇第 2 列作為篩選行以查找我的兩個文件之間的唯一和常見條目的行。 如果第二列中的條目出現在兩個文件中,我還想記錄第 3,4 和 5 列中的信息(如果可能,這並不重要)。 這是輸入和輸出的示例。
FILE1.txt
NM_023928 AACS 2 2 1
NM_182662 AADAT 2 2 1
NM_153698 AAED1 1 5 3
NM_001271 AAGAB 2 2 1
FILE2.txt
NM_153698 AAED1 2 5 3
NM_001271 AAGAB 2 2 1
NM_001605 AARS 3 40 37
NM_212533 ABCA2 3 4 2
想要的輸出:
COMMON.txt
NM_153698 AAED1 1 5 3 2 5 3
NM_001271 AAGAB 2 2 1 2 2 1
UNIQUE_TO_1.txt
NM_023928 AACS 2 2 1
NM_182662 AADAT 2 2 1
UNIQUE_TO_2.txt
NM_001605 AARS 3 40 37
NM_212533 ABCA2 3 4 2
我知道以前有過類似的問題,但我無法完全找到我要找的東西。 任何想法都非常感謝,謝謝。
join
具有以下對您的任務有用的選項:
-j FIELD
: 加入字段FIELD
-o FORMAT
:指定輸出格式,以逗號分隔的 FILENUM.FIELD 列表。-v FILENUM
:僅在FILENUM
上輸出行。兩個文件的共同點:
$ join -j2 -o 1.1,1.2,1.3,1.4,1.5,2.3,2.4,2.5 FILE1.txt FILE2.txt
NM_153698 AAED1 1 5 3 2 5 3
NM_001271 AAGAB 2 2 1 2 2 1
FILE1 獨有:
$ join -j2 -v1 FILE1.txt FILE2.txt
AACS NM_023928 2 2 1
AADAT NM_182662 2 2 1
FILE2 的獨特之處:
$ join -j2 -v2 FILE1.txt FILE2.txt
AARS NM_001605 3 40 37
ABCA2 NM_212533 3 4 2
您可以使用 gnu awk 對其進行歸檔,這是一個腳本:
腳本.awk
function unique(filename, line) {
split( line , tmp, FS)
print tmp[1], tmpp[2], tmp[3], tmp[4], tmp[5] >> filename
}
NR == FNR { # in case we are reading the first file: store line under key
file1[ $2 ] = $0
next
}
{
if( $2 in file1 ) { # key from file2 was in also in file1:
split( file1[ $2 ], tmp, FS)
print $1, $2, tmp[3], tmp[4], tmp[5], $3, $4, $5 >> "COMMON.txt"
# remove common key, thus we can later find unique keys from file1
delete file1[ $2 ]
}
else { # unique key from file2
unique("UNIQUE_TO_2.txt", $0)
}
}
END {
# remaining keys are unique in file1
for( k in file1 ) {
unique("UNIQUE_TO_1.txt", file1[ k ])
}
}
像這樣使用它:
# erase the output files if present
rm -f COMMON.txt UNIQUE_TO_1.txt UNIQUE_TO_2.txt
# run script, create the file
awk -f script.awk FILE1.txt FILE2.txt
# output the files
for f in COMMON.txt UNIQUE_TO_1.txt UNIQUE_TO_2.txt; do echo "$f"; cat "$f"; done
printf ... >> filename
名將文本附加到文件名。 第二次運行腳本時,這需要輸出文件的rm
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.