2014-01-24 74 views
1

我有2個文件file1和file2。我正在嘗試從file1讀取一行,並從file2讀取另一行,並插入HTML 標誌以使其在html文件中成爲usealbe。我一直試圖與awk一起工作,但收效甚微。有人可以幫忙嗎?在UNIX中一次讀取兩行文本文件一行

File1中:

SILOS.SIL_Stage_GroupAccountNumberDimension_FinStatementItem 
SDE_ORA11510_Adaptor.SDE_ORA_Stage_GLAccountDimension_FinSubCodes 

文件2:

FlatFileConnection.DBConnection_OLAP.SILOS.SIL_Stage_GroupAccountNumberDimension_FinStatementItem.txt 
FlatFileConnection.DBConnection_OLAP.SDE_ORA11510_Adaptor.SDE_ORA_Stage_GLAccountDimension_FinSubCodes.txt 

希望的輸出:

<ParameterFile> 
<workflow>SILOS.SIL_Stage_GroupAccountNumberDimension_FinStatementItem</workflow> 
<File>FlatFileConnection.DBConnection_OLAP.SILOS.SIL_Stage_GroupAccountNumberDimension_FinStatementItem.txt</File> 
<ParameterFile> 
<workflow>SDE_ORA11510_Adaptor.SDE_ORA_Stage_GLAccountDimension_FinSubCodes</workflow> 
<File>FlatFileConnection.DBConnection_OLAP.SDE_ORA11510_Adaptor.SDE_ORA_Stage_GLAccountDimension_FinSubCodes.txt</File> 
+1

_很少成功_ - 它會很高興地顯示你的嘗試。用於awk解決方案的 – devnull

回答

2

使用bash:

printItem() { printf "<%s>%s</%s>\n" "$1" "${!1}" "$1"; } 

paste file1 file2 | 
while read workflow File; do 
    echo "<ParameterFile>" 
    printItem workflow 
    printItem File 
done 

使用awk,這將是:

awk ' 
    NR==FNR {workflow[FNR]=$1; next} 
    { 
     print "<ParameterFile>" 
     printf "<workflow>%s</workflow>\n", workflow[FNR] 
     printf "<File>%s</File>\n", $1 
    } 
' file1 file2 

不需要存儲第一個文件在內存中的另一種方法:

awk '{ 
    print "<ParameterFile>" 
    print "<workflow>" $0 "</workflow>" 
    getline < "file2" 
    print "<File>" $0 "</File>" 
}' file1 
+0

+1。我從來沒有見過「$ {!1}」,所以也很高興能夠了解這一點(我已經評估過了)。儘管任何輸入文件中都可能出現空格或反斜槓,但我實際上不會在bash中使用這種方法。 –

1

如果你不介意在一些殼混合:

$ paste -d$'\n' file1 file2 | 
awk '{ printf (NR%2 ? "<ParameterFile>\n<workflow>%s</workflow>\n" : "<File>%s</File>\n"), $0 }' 
<ParameterFile> 
<workflow>SILOS.SIL_Stage_GroupAccountNumberDimension_FinStatementItem</workflow> 
<File>FlatFileConnection.DBConnection_OLAP.SILOS.SIL_Stage_GroupAccountNumberDimension_FinStatementItem.txt</File> 
<ParameterFile> 
<workflow>SDE_ORA11510_Adaptor.SDE_ORA_Stage_GLAccountDimension_FinSubCodes</workflow> 
<File>FlatFileConnection.DBConnection_OLAP.SDE_ORA11510_Adaptor.SDE_ORA_Stage_GLAccountDimension_FinSubCodes.txt</File> 

否則請參閱@ GlennJackman的純awk方法來解決此問題。

+1

這三種解決方案都很好。謝謝你們的幫助。 – user3232642

相關問題