2016-05-13 21 views
1

我有三個不同的列和行大小的文件。例如,如何在awk中添加特殊字符?

ifile1.txt  ifile2.txt  ifile3.txt 
    1 2 2  1 6   3  8 
    2 5 6  3 8   9  0 
    3 8 7  6 8   23  6 
    6 7 6  23 6   44  5 
    9 87 87  44 7   56  7 
23 6 6  56 8   78 89 
44 5 76  99 0   95 65 
56 6 7      99 78 
78 7 8      106  0 
95 6 7      110  6 
99 6 4     
106 5 34     
110 6 4     

Here ifile1.txt has 3 coulmns and 13 rows, 
    ifile2.txt has 2 columns and 7 rows, 
    ifile3.txt has 2 columns and 10 rows. 
    1st column of each ifile is the ID, 
    This ID is sometimes missing in ifile2.txt and ifile3.txt. 

我想作一個outfile.txt有4列,其第一列會對所有的ID在ifile1.txt,而第二coulmn爲$ 3從ifile1.txt,第3和ifile2.txt和ifile3.txt的第4列將是$ 2,ifile2.txt和ifile3.txt中的缺失站點將被指定爲特殊字符「?」。

慾望輸出:

outfile.txt 
    1  2  6  ? 
    2  6  ?  ? 
    3  7  8  8 
    6  6  8  ? 
    9 87  ?  0 
23  6  6  6 
44 76  7  5 
56  7  8  7 
78  8  ? 89 
95  7  ? 65 
99  4  0 78 
106 34  ?  0 
110  4  ?  6 

我是用下面的算法很努力,但能不能寫一個腳本。

for each i in $1, awk '{printf "%3s %3s %3s %3s\n", $1, $3 (from ifile1.txt), 
check if i is present in $1 (ifile2.txt), then 
      write corresponding $2 values from ifile2.txt 
     else write ? 
similarly check for ifile3.txt 
+0

對於我們來測試潛在的解決方案,我們必須手動拉開你的問題中的什麼來創建3個輸入文件。我懷疑是否有許多人會這麼做 - 編輯你的問題,以單獨顯示3個輸入文件,而不是粘貼在一起,以便我們更容易,所以我們更有可能幫助你。並且使每個文件大約3-5行,每個文件不需要10行以上的樣本輸入。 –

回答

1

你可以做到這一點與使用GNU AWK此腳本:

script.awk

# read lines from the three files 
ARGIND == 1 { file1[ $1 ] = $3 
       # init the other files with ? 
       file2[ $1 ] = "?" 
       file3[ $1 ] = "?" 
       next; 
      } 

ARGIND == 2 { file2[ $1 ] = $2 
       next; 
      } 

ARGIND == 3 { file3[ $1 ] = $2 
       next; 
      } 

# output the collected information 
END   { for(k in file1) { 
       printf("%3s%6s%6s%6s\n", k, file1[ k ], file2[ k ], file3[ k ]) 
       } 
      } 

運行腳本是這樣的:awk -f script.awk ifile1.txt ifile2.txt ifile3.txt > outfile.txt