【问题标题】:sed stream editor unix linux command : how to keep retain a paragraph with a particular text stringsed 流编辑器 unix linux 命令:如何保留带有特定文本字符串的段落
【发布时间】:2010-12-14 10:47:12
【问题描述】:

我设法通过用空行分隔文本将它们放入文件中。我试图只保留那些具有特定字符串的段落。虽然 Sed 常见问题解答提到了一个解决方案,但它不起作用(参见下面的示例)

http://www.catonmat.net/blog/sed-one-liners-explained-part-two/

58. Print a paragraph that contains “AAA”. (Paragraphs are separated by blank lines).
sed -e '/./{H;$!d;}' -e 'x;/AAA/!d;'

http://www.linuxhowtos.org/System/sedoneliner.htm?ref=news.rdf

# print paragraph if it contains AAA (blank lines separate paragraphs)
# HHsed v1.5 must insert a 'G;' after 'x;' in the next 3 scripts below
sed -e '/./{H;$!d;}' -e 'x;/AAA/!d;'

你能告诉我为什么它不工作吗?另外,如果您知道使用 unix 工具或其他方式的解决方案,请告诉我。

【问题讨论】:

  • 哎呀,这很难读。你能重新格式化你的问题吗?
  • 刚刚通过获取一些 Lorem ipsum 并用各种单词替换 'AAA' 进行了测试,它似乎像宣传的那样工作:sed -e '/./{H;$!d;}' -e 'x;/Pellentesque/!d;' lipsum.txt
  • 你能比“不工作”更具体吗?

标签: linux unix text sed paragraph


【解决方案1】:

对于文件解析,请改用 gawk。仅将 sed 用于简单替换。

awk -vRS= '/AAA/' file

输出:

$ more file
text
text
BBB
text

text
text
AAA
text

text
text
CCC
text

$ awk -vRS= '/AAA/' file
text
text
AAA
text

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-29
    • 1970-01-01
    • 2020-03-30
    • 1970-01-01
    • 2020-08-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多