在UNIX中一次读取2行文本文件

时间:2014-01-24 15:54:29

标签: awk

我有2个文件,file1和file2。我试图从file1读取一行并从file2读取另一行并插入HTML 要制作的标志是一个html文件中的usealbe。我一直试图用awk工作但收效甚微。有人可以帮忙吗?

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>

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

如果你不介意混合一些shell:

$ 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方法。