使用 awk 插入第二个文件内容

使用 awk 插入第二个文件内容

我正在尝试使用 .xml 将整个第二个文件内容(它是一个日志)附加到 XML<log>标记中awk。我无法将两个输入文件合并为一个,因为我使用的FS="\n" RS="\n\n"是适合我的第一个输入文件的文件。我无法确定我的awk代码之间应该包含哪一部分。<log>WHAT_TO_FEED_HERE?</log>

任何建议都会非常有帮助。

输入文件1:

Sara
123
[email protected]

John
456
[email protected]

输入文件2:

#This is first line along with # symbol

#There were two blank lines spaces above
#Candidatedata1 values

#Some more random text

我需要最终输出如下:

<name>Sara</name>
<id>123</id>
<email>[email protected]</email>
<log>
#This is first line along with # symbol

#There were two blank lines spaces above
#Candidatedata1 values

#Some more random text
</log>

<name>John</name>
<id>456</id>
<email>[email protected]</email>
<log>
#This is first line along with # symbol

#There were two blank lines spaces above
#Candidatedata2 values

#Some more random text
</log>

我使用了以下awk语句:

awk 'BEGIN{FS = "\\n";RS = "\\n\\n"; print " "}
  { print "<candidate>" }
  { print "<name>"$1"</name>" }
  { print "<id>"$2"</id>" }
  { print "<email>"$3"</email>" }
  { print "<log>"WHAT_TO_FEED_HERE?"</log>" }
  { print "</candidate>" }
  {print " " }' Input_file1.txt Input_file2.txt> candidatefinaloutput.xml

答案1

当您不想对所有文件应用相同的处理时,awk 有点麻烦,但这是可以做到的。

对于这个用例,我会在开始时读取第二个文件的内容,然后使用它。

BEGIN {
    while (getline <ARGV[2]) {
        logfile = logfile $0 "\n"
    }
    delete ARGV[2];
    FS = "\\n"; RS = "\\n\\n";
}
{
    print "<candidate>";
    print "<name>" $1 "</name>";
    print "<id>" $2 "</id>";
    print "<email>" $3 "</email>";
    print "<log>" logfile "</log>";
    print "</candidate>";
    print "";
}

相关内容