sed one-liner - 查找定界符对周围的关键字

时间:2012-07-20 22:51:49

标签: xml bash sed grep

我通常使用大型XML文件,通常会通过grep进行字数统计来确认某些统计信息。

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

cat test.xml | grep -ic widget

此外,我只想记录widget出现的行,即:

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

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

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

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

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

<test>widget</test>

<formula>widget</formula>

实际上,我正在尝试使用最高级别的标记标记获得一行,这些标记适用于围绕任意字符串widget的XML文本/代码块。

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

谢谢。

4 个答案:

答案 0 :(得分:3)

使用sedawk的非优雅方式:

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 }'

结果:

<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

答案 1 :(得分:2)

 sed -nr '/^(<[^>]*>).*/{s//\1/;h};/widget/{g;p}' test.xml

打印

<test>
<formula>

如果打印出您想要的确切格式,则只有单行内容会更复杂。

修改
您可以使用/widget/I代替/widget/,以便在gnu sed中对widget进行不区分大小写的匹配,否则在每个字母中使用[Ww],就像在另一个答案中一样。

答案 2 :(得分:2)

这可能适合你(GUN sed):

sed '/^<[^/]/!d;:a;/^<\([^>]*>\).*<\/\1/!{$!N;ba};/^<\([^>]*>\).*\(widget\).*<\/\1/s//<\1\2<\/\1/p;d' file

答案 3 :(得分:1)

需要gawk才能在RS

中使用正则表达式
BEGIN {
    # make a stream of words
    RS="(\n| )"
}

# match </tag>
/<\// {
    s--
    next
}

# match <tag>
/</ {
    if (!s) {
    tag=substr($0, 2)
    }
    s++
}

$0=="widget" {
    print "<" tag $0 "</" tag
}