Unix 如何在shell中字符串匹配的第三行之后添加一些文本

Unix 如何在shell中字符串匹配的第三行之后添加一些文本,unix,Unix,我有一个xml文件。我想在匹配模式“已发行发票总额””的第三行之后添加一行“新文本”。如何在shell脚本中实现这一点 输入文件[Form.xml] <Formula> <ename>Total Invoices Released</ename> <comment></comment> <Type>Suspense</Type> <tags> <tags>Total Invoice Rel

我有一个xml文件。我想在匹配模式“
已发行发票总额”
”的第三行之后添加一行“新文本”。如何在shell脚本中实现这一点

输入文件[Form.xml]

<Formula>
<ename>Total Invoices Released</ename>
<comment></comment>
<Type>Suspense</Type>
<tags>
<tags>Total Invoice Released</tags>
<tags>Total Invoices Released</tags>
<tags>Total Invoices Released</tags>

发出的发票总额
悬念
已开具发票总额
发出的发票总额
发出的发票总额
我使用了下面的代码,但不起作用

sed -n "/<ename>Total Invoices Released</ename>/{N;N;N;a new_text}" Form.xml
sed-n”/Total Invoices Released/{n;n;n;a new_text}Form.xml
输出文件应如下所示

<Formula>
<ename>Total Invoices Released</ename>
<comment></comment>
<Type>Suspense</Type>
<tags>
a new_text
<tags>Total Invoice Released</tags>
<tags>Total Invoices Released</tags>
<tags>Total Invoices Released</tags>

发出的发票总额
悬念
新课文
已开具发票总额
发出的发票总额
发出的发票总额
这样的程序:

# It stores if the searched text has been matched, or not
matched=false
# The quantity of lines that have been read after the searched text has been matched
linesAfterMatched=0

while IFS= read -r line; do 
    echo "$line"
    if [[ "$matched" == false ]]; then
        if [[ "$line" == "<ename>Total Invoices Released</ename>" ]]; then
            matched=true
        fi
    else
        ((linesAfterMatched += 1))
        if [[ "$linesAfterMatched" == 3 ]]; then
            echo "a new text!"
        fi
    fi
done
#它存储搜索的文本是否匹配
匹配=错误
#匹配搜索文本后读取的行数
linesAfterMatched=0
而IFS=读取-r行;做
回音“$line”
如果[[“$matched”==false]];然后
如果[[“$line”==“已发放发票总额”];然后
匹配=真
fi
其他的
((linesAfterMatched+=1))
如果[[“$linesaffermatched”==3]];然后
回声“一个新的文本!”
fi
fi
完成
可以这样使用:

program.sh < Form.xml
program.sh
并显示:

<Formula>
<ename>Total Invoices Released</ename>
<comment></comment>
<Type>Suspense</Type>
<tags>
a new text!
<tags>Total Invoice Released</tags>
<tags>Total Invoices Released</tags>
<tags>Total Invoices Released</tags>

发出的发票总额
悬念
新文本!
已开具发票总额
发出的发票总额
发出的发票总额

与我用awk或sed尝试的一些替代方案不同,它非常可定制(而且更容易)。

您好,这很有效。有点怀疑。如果我想用现有模式搜索xml文件中的另一个模式,并在serached模式的第三行之后添加另一个模式。我该怎么做?嗨!这变得越来越复杂。StackOverflow中的标准过程是向上投票,然后创建另一个问题(您可以在其中放置指向当前问题的链接)。