user3232642
user3232642

Reputation: 13

Reading from 2 text files one line at a time in UNIX

I have 2 files, file1 and file2. I am trying to read one line from file1 and read another line from file2 and insert HTML flags to make is usealbe in an html file. I have been trying to work with awk with little success. Can someone please help?

File1:

SILOS.SIL_Stage_GroupAccountNumberDimension_FinStatementItem
SDE_ORA11510_Adaptor.SDE_ORA_Stage_GLAccountDimension_FinSubCodes

File2:

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

Desired output:

<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>

Upvotes: 1

Views: 100

Answers (2)

glenn jackman
glenn jackman

Reputation: 247220

Using 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

With awk, it would be:

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

Another approach that does not require storing the first file in memory:

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

Upvotes: 3

Ed Morton
Ed Morton

Reputation: 204721

If you don't mind mixing in some 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>

otherwise see @GlennJackman's solution for the pure awk way to do it.

Upvotes: 1

Related Questions