Grep 和 Split 基于 Pattern - shell 脚本



>我有一个大文本文件,其模式如下:

CAT:D1_XCAT_TE_ID=SE0101900     
CAT:D2_XCAT_TE_ID=SF0101900
CAT:D3_XCAT_TE_ID=SG0101900
.
.
.
.
.
.
DLR:1|1|1|606|P|1|1|
DLR:1|2|1|606|P|1|1|
DLR:1|3|1|606|F|1|1|
.
.
.
CAT:D1_XCAT_TE_ID=D0101901
CAT:D2_XCAT_TE_ID=D0101902
CAT:D3_XCAT_TE_ID=D0101903
.
.
.
DLR:1|1|1|607|P|1|1|
DLR:1|2|1|607|P|1|1|
DLR:1|3|1|607|P|1|1|

我需要做的是我需要获取关键字"XCAT_TE_ID"。例:

Each of CAT:D1xxx will have one DLR:1|1|xxx
CAT:D2xxx will have one DLR:1|2|xxx
CAT:D3xxx will have one DLR:1|3|xxx
Original :
CAT:D1_XCAT_TE_ID=SE0101900
After split:
D1_XCAT_TE_ID - store in one array
SE0101900 - store in another array

但是,如果只有第 5 个字段的值是 DLR 中的"P"(除以 |(,则存储在数组中的条件。

为了获得 CAT 的 DLR:

CAT:D1_XCAT_TE_ID=SE0101900
D1 - this field, number 1 indicates the DLR
To refer to the value of DLR, split the DLR with "|" and get the 2nd field.
2nd field= 1
then, the value of DLR will be:
DLR:1|1|1|607|P|1|1|
each of CAT record has one DLR record. This is a pair. 

但是,如果只有第 5 个字段的值是来自 DLR(除以 |(的"P",我需要存储该值。 我不知道该怎么做。请帮忙。

使用awk,您可以读取一次输入文件,并且比这些重复的命令工作得更快。 我不知道你对awk的经验,所以我给出了这个缓慢的选择。
首先查找不同的DLR

sed -rn 's/^CAT:D([^_]*).*/1/p' inputfile| sort -u

-r/p的组合可确保仅打印匹配项。
此命令将是下一个循环的输入(done之后(:

while IFS= read -r dlr; do
grep -E "^CAT:D${dlr}_|^DLR:[^|]*|${dlr}|" inputfile |
paste -d"=" - - |
sed -rn 's/[^=]*=([^=]*)=DLR:([^|]*|){4}P.*/1/p'
done < <(sed -rn 's/^CAT:D([^_]*).*/1/p' inputfile | sort -u)

此解决方案假设 DLR 记录只有一个=(我可以在粘贴命令中使用它(,并且在每个 CAT 记录之后只有一个匹配的 DLR 记录。

首先,仅选择相关的行:

# results without paste processing
CAT:D1_XCAT_TE_ID=SE0101900
DLR:1|1|1|606|P|1|1|
CAT:D1_XCAT_TE_ID=D0101901
DLR:1|1|1|607|P|1|1|
CAT:D2_XCAT_TE_ID=SF0101900
DLR:1|2|1|606|P|1|1|
CAT:D2_XCAT_TE_ID=D0101902
DLR:1|2|1|607|P|1|1|
CAT:D3_XCAT_TE_ID=SG0101900
DLR:1|3|1|606|F|1|1|
CAT:D3_XCAT_TE_ID=D0101903
DLR:1|3|1|607|P|1|1|

接下来,paste命令连接每对行

# result without `sed` command (spaces of first record are in the example input)
CAT:D1_XCAT_TE_ID=SE0101900     =DLR:1|1|1|606|P|1|1|
CAT:D1_XCAT_TE_ID=D0101901=DLR:1|1|1|607|P|1|1|
CAT:D2_XCAT_TE_ID=SF0101900=DLR:1|2|1|606|P|1|1|
CAT:D2_XCAT_TE_ID=D0101902=DLR:1|2|1|607|P|1|1|
CAT:D3_XCAT_TE_ID=SG0101900=DLR:1|3|1|606|F|1|1|
CAT:D3_XCAT_TE_ID=D0101903=DLR:1|3|1|607|P|1|1|

现在sed用于选择带有|P的行并显示子字符串。

最新更新