sed one-liner - 查找关键字周围的分隔符对

2024-01-03

我通常使用大型 XML 文件,并且通常通过以下方式进行字数统计:grep确认某些统计数据。

例如,我想确保至少有五个实例widget通过以下方式在单个 xml 文件中:

cat test.xml | grep -ic widget

此外,我只是希望能够记录以下行widget出现在,即:

cat test.xml | grep -i widget > ~/log.txt

然而,我真正需要的关键信息是 XML 代码块widget出现在。示例文件可能如下所示:

<test> blah blah
  blah blah blah
  widget
  blah blah blah
</test>

<formula>
  blah
  <details> 
    widget
  </details>
</formula>

我试图从上面的示例文本中获得以下输出,即:

<test>widget</test>

<formula>widget</formula>

实际上,我正在尝试获取具有最高级别标记标签的单行,这些标记标签适用于围绕任意字符串的 XML 文本/代码块,widget.

有没有人对通过命令行单行实现这一点有任何建议?

谢谢。


使用两者的一种不优雅的方式sed and awk:

sed -ne '/[Ww][Ii][Dd][Gg][Ee][Tt]/,/^<\// {//p}' file.txt | awk 'NR%2==1 { sub(/^[ \t]+/, ""); search = $0 } NR%2==0 { end = $0; sub(/^<\//, "<"); printf "%s%s%s\n", $0, search, end }'

Results:

<test>widget</test>
<formula>widget</formula>

解释:

## The sed pipe:

sed -ne '/[Ww][Ii][Dd][Gg][Ee][Tt]/,/^<\// {//p}'
## This finds the widget pattern, ignoring case, then finds the last, 
## highest level markup tag (these must match the start of the line)
## Ultimately, this prints two lines for each pattern match

## Now the awk pipe:

NR%2==1 { sub(/^[ \t]+/, ""); search = $0 }
## This takes the first line (the widget pattern) and removes leading
## whitespace, saving the pattern in 'search'

NR%2==0 { end = $0; sub(/^<\//, "<"); printf "%s%s%s\n", $0, search, end }
## This finds the next line (which is even), and stores the markup tag in 'end'
## We then remove the slash from this tag and print it, the widget pattern, and
## the saved markup tag

HTH

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

sed one-liner - 查找关键字周围的分隔符对 的相关文章

随机推荐