2015-06-12 180 views
0

我正處於學習shell腳本的初始階段。所以請給我解釋一下更好理解的步驟。使用awk命令比較字符串

考慮我有兩個文件

兩個文件的

內容有如下:

FILE1.TXT

ABC=10 
DEF=20 
XYZ=30 

FILE2.TXT

DEF=15 
XYZ=20 

我想寫一個簡單的shell腳本來檢查這兩個文件並添加值並將最終輸出結果打印爲b elow。像

ABC=10 
DEF=35 
XYZ=50 

回答

0

您可以使用AWK:

awk 'BEGIN{FS=OFS="="} FNR==NR{a[$1]=$2;next} {a[$1]+=$2} 
    END{for (i in a) print i, a[i]}' file1 file2 
ABC=10 
XYZ=50 
DEF=35 

破碎:

NR == FNR {     # While processing the first file 
    a[$1] = $2     # store the second field by the first in an array 
    next      # move to next record 
} 
{       # while processing the second file 
    a[$1]+=$2     # add already stored value by 2nd field in 2nd file         
} 
END{..}      # iterate the array and print the values 

如果你想保持原來的順序不變,然後使用:

awk 'BEGIN{FS=OFS="="} FNR==NR{if (!($1 in a)) b[++n]=$1; a[$1]=$2;next} {a[$1]+=$2} 
    END{for (i=1; i<=n; i++) print b[i], a[b[i]]}' file1 file2 
ABC=10 
DEF=35 
XYZ=50 
+0

感謝您回覆我的查詢,請詳細解釋我,因爲我對腳本/編程非常陌生。 – suru1432002