awk - 使用egrep但开始认为awk或sed可能是解决方案

标签 awk sed grep posix

首先,我使用 Cygwin mintty 2.7.4 所以... posix。我的文件中存在多个类似于以下内容的代码片段:

<blah>Spread the peanut butter <ramout assot="f0123_fun10" bapel="2 or 6"/> on good looking bread <ramout assot="f0123_fun10" bapel="3 or 5"/> that does not have peanut butter <ramout assot="f0123_fun10" bapel="2 or 6"/> already on the bread this that and the other <ramout assot="f0123_fun10" bapel="4"/> with something else.</blah>

我正在尝试在一组 blah 标签内查找 ramout 标签的重复实例。 如果存在以下情况:

<ramout assot="f0123_fun10" bapel="2 or 6"/> 

我想知道它是否在一组开始和结束的 blah 标签中再次重复。

我尝试过多种方法。最新的一项如下:

grep -Eoi '<blah>.*([[:space:]]<ramout assot).*\1.*</blah>' *.xml | less

什么也没返回。

我也尝试过:

 grep -Eio '<blah>.*([[:space:]]<ramout assot="[a-z][0-9]{5}_fig[0-9]+" bapel="[0-9]+.*)' *.xml

其中不包括可得出结果但不显示所有结果的反向引用。看起来这仅显示一行/不跨越多行的结果。

如果我想搜索可能或可能不在一行的内容,我应该使用 sed 吗?

awk 是一个可行的候选者吗?我看到并尝试了: awk '/Startpattern/,/Endpattern/' filename 返回了更多结果,但我仍然没有得到所有结果。

任何能够找到 a) 整个文件中的所有 ramout 结果以及单独 b) 在 blah 标签内重复的所有 ramout 结果的帮助将不胜感激。

预期结果类似于:

搜索结果 a) 显示所有 ramout 结果:

<ramout assot="f0123_fun10" bapel="2 or 6"/>
<ramout assot="f0123_fun10" bapel="3 or 5"/>
<ramout assot="f0123_fun10" bapel="2 or 6"/>
<ramout assot="f0123_fun10" bapel="4"/>

搜索 b) 的结果显示重复的结果将显示:

<ramout assot="f0123_fun10" bapel="2 or 6"/>

最佳答案

要解析/查询 XML/XHTML 文档,请使用以下工具之一:

  • xmlstarlet
  • xmllint
  • 撒克逊林特

我将使用xmlstarlet建议解决方案.
1) 安装 xmlstarlet工具
2) 使用XmlStarlet selectsel查询或搜索 XML 文档的选项 ( xmlstarlet manual )


a) 全部 <ramout>整个文件中的标签:

xmlstarlet sel -t -n  -m "//blah/ramout" -c "." -n testfile.xml

输出:

<ramout assot="f0123_fun10" bapel="2 or 6"/>
<ramout assot="f0123_fun10" bapel="3 or 5"/>
<ramout assot="f0123_fun10" bapel="2 or 6"/>
<ramout assot="f0123_fun10" bapel="4"/>

b) 全部 <ramout> <blah> 内重复的标签标签:

xmlstarlet sel -t -n  -m "//blah/ramout" -c "." -n testfile.xml | sort | uniq -d

输出:

<ramout assot="f0123_fun10" bapel="2 or 6"/>

uniq -d :
-d, --repeated - 只打印重复的行,每组一个

关于awk - 使用egrep但开始认为awk或sed可能是解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42741584/

相关文章:

linux - 如何在 Linux 服务器上查找和替换 HTML、htm、PHP 和 txt 文件中的文本?

Linux根据文件名模式批量复制文件到目录

regex - 如何在 mac os x (BSD) sed 上转义加号?

python - 从多个文件中提取一列并将其粘贴到一个文件中

linux - 格式化和过滤文件到 Csv 表

linux - 使用 awk 或 sed 比较多个文件的长度

bash - 如何更改 .dat 文件中特定列的值 | bash

linux - BASH - 删除行并用空行替换它们

bash - sh 和 bash 中 pgrep 的区别

linux - 从 bash 中的 Json 中提取值