簡體   English   中英

根據兩個文件的條件+列匹配來生成新文件

[英]Generate a new file based on a condition + column matching of two files

首先,如果在發布之前沒有遇到類似的答案,我們深表歉意。

我正在嘗試根據幾種條件創建第三個文件。

我有兩個輸入文件

file1(制表符分隔):-

X_ID1 y_id11 num1
X_ID2 y_id31 num2  
X_ID3 y_id34 num3 
X_ID4 y_id23 num4
X_ID5 y_id2  num5 
...  
...  

文件2:-

BIOTIC AND ABIOTIC STRESS
x_id2
REGULATION OF TRANSCRIPTION
x_id1
x_id4
HORMONES
x_id5
REGULATION
x_id6
x_id13
...
...

****請注意,文件1的第1列為大寫,文件2中的數據為小寫

我想要的是輸出文件(file3)如下:

BIOTIC AND ABIOTIC STRESS
y_id31
REGULATION OF TRANSCRIPTION
y_id11
y_id23
HORMONES
y_id2
...
...

基本上,如果我想到一個“偽代碼”,它會如下所示:-

while read $line from file2; do
 if [[line1 != x_*]]; then
    print $line
 else
    match $line (case insensitively) with column 1 of file1 and print respective column2 of file1
 fi
done 

您能幫我解決這個問題嗎?

在此先多謝!

在awk中:

$ awk 'NR==FNR{a[tolower($1)]=$2;next}{print ($1 in a?a[$1]:$0)}' file1 file2
BIOTIC AND ABIOTIC STRESS
y_id31
REGULATION OF TRANSCRIPTION
y_id11
y_id23
HORMONES
y_id2
REGULATION
x_id6
x_id13

解釋:

$ awk '
NR==FNR {                    # first file
    a[tolower($1)]=$2        # hash to a, key is lowercase $1 data is $2
    next                     # skip tp next record
}
{                            # second file
    print ($1 in a?a[$1]:$0) # if $1 exists in hash a, print it, else print current
}' file1 file2               # mind the order

根據@Sundeep的建議, 是awk中兩個文件處理的一個很好的介紹。

OLD_IFS="${IFS}"
IFS=$'\n'
for line in `cat file2`
do
        if [[ -z `echo "${line}" | grep x_*`  ]]
        then
                echo "${line}"
        else
                grep -i "${line}" file1 | awk -F ' ' '{print $2}'
        fi
done
IFS="${OLD_IFS}"

可以通過一個while循環來完成:

while IFS= read -r line;
do
   var=`echo $line | tr '[a-z]' '[A-Z]'`
   col2=`grep "$var" file1|cut -d" " -f2`
   if [[ -z "$col2" ]] ; then
        echo "$line" >> file3
    else
        echo "$col2"  >> file3
   fi

done < file2

說明:-

var=echo $line | tr '[az]' '[AZ]' var=echo $line | tr '[az]' '[AZ]' -將小寫字母轉換為大寫字母。

col2=grep "$var" file1|cut -d" " -f2匹配文件1中的模式。 如果沒有匹配項,即變量col2為空,則將line寫入文件file3,否則將col2寫入文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM