根据 1 行插入来自 2 个文件的变量

根据 1 行插入来自 2 个文件的变量

我有 3 个源文件。

1.txt- 模板。

<field name="COL1" label="COL2" data-source="COL1" classes="attribute" category="Attribute"/>

2.txt- COL1 的变量。

IDNName
BusinessUnit
WWB
IncentiveID

3.txt- COL2 的变量。

IDN Name
Business Unit
WWB
Incentive ID

我需要这样的输出(从和中取出第一行2.txt3.txt插入到模板中,然后从和中取出第二行2.txt3.txt插入到模板中,等等......)

<field name="IDNName" label="IDN Name" data-source="IDNName" classes="attribute" category="Attribute"/>
<field name="BusinessUnit" label="Business Unit" data-source="BusinessUnit" classes="attribute" category="Attribute"/>
<field name="WWB" label="COL2" data-source="WWB" classes="attribute" category="Attribute"/>
<field name="IncentiveID" label="Incentive ID" data-source="IncentiveID" classes="attribute" category="Attribute"/>

for是否可以通过一个条件来实现sed?我试过了,但我不知道如何将两个文件合并到一行中。

for i in $(cat 2.txt); do cat 1.txt | sed 's/COL1/'$i'/g'; echo; done

谢谢。

答案1

如果你知道在你的 2.txt 或 3.txt 文件中可能不会出现“安全”分隔符(如 TAB),那么你可以这样做

$ paste 2.txt 3.txt | while IFS=$'\t' read -r src lbl; do 
    sed -e 's/"COL1"/"'"$src"'"/g' -e 's/"COL2"/"'"$lbl"'"/' 1.txt
  done
<field name="IDNName" label="IDN Name" data-source="IDNName" classes="attribute" category="Attribute"/>
<field name="BusinessUnit" label="Business Unit" data-source="BusinessUnit" classes="attribute" category="Attribute"/>
<field name="WWB" label="WWB" data-source="WWB" classes="attribute" category="Attribute"/>
<field name="IncentiveID" label="Incentive ID" data-source="IncentiveID" classes="attribute" category="Attribute"/>

或者使用 GNU parallel:

$ parallel --link sed -e 's/"COL1"/"{1}"/g' -e 's/"COL2"/"{2}"/' 1.txt :::: 2.txt 3.txt
<field name="IDNName" label="IDN Name" data-source="IDNName" classes="attribute" category="Attribute"/>
<field name="BusinessUnit" label="Business Unit" data-source="BusinessUnit" classes="attribute" category="Attribute"/>
<field name="WWB" label="WWB" data-source="WWB" classes="attribute" category="Attribute"/>
<field name="IncentiveID" label="Incentive ID" data-source="IncentiveID" classes="attribute" category="Attribute"/>

但是如果你实际使用的是 XML 数据,那么你可能需要使用合适的 XML 工具 - 这xmlstarlet是一种可能性,但由于我更熟悉,因此这里jq可以选择使用 kislyuk 的xqyq:命令行 YAML/XML/TOML 处理器 - YAML、XML、TOML 文档的 jq 包装器

$ xq -x --rawfile src 2.txt --rawfile lbl 3.txt '
    foreach ([($src | split("\n")[0:-1]), ($lbl | split("\n")[0:-1])] | transpose[]) as $a
      (.; .field |= (."@name" |= $a[0] | ."@label" |= $a[1] | ."@data-source" |= $a[0]))
' 1.txt
<field name="IDNName" label="IDN Name" data-source="IDNName" classes="attribute" category="Attribute"></field>
<field name="BusinessUnit" label="Business Unit" data-source="BusinessUnit" classes="attribute" category="Attribute"></field>
<field name="WWB" label="WWB" data-source="WWB" classes="attribute" category="Attribute"></field>
<field name="IncentiveID" label="Incentive ID" data-source="IncentiveID" classes="attribute" category="Attribute"></field>

相关内容