【问题标题】:Looking for a one-liner to remove duplicate multiline paragraphs from a file寻找一个单行从文件中删除重复的多行段落
【发布时间】:2014-10-21 20:35:12
【问题描述】:
File:
this is a paragraph
to find in another 
file

some stuff .. 

more stuff ... 

this is a paragraph
to find in another 
file

more stuff ... 

another paragraph 
to match

yet more stuff.. 

this is a paragraph
duplicate in this 
file

another paragraph 
to match 

this is a paragraph
duplicate in this 
file

yet more stuff..

this is a paragraph
to find in another
file

应该返回:

this is a paragraph
to find in another 
file

some stuff .. 

more stuff ... 

more stuff ... 

another paragraph 
to match

yet more stuff.. 

this is a paragraph
duplicate in this 
file

yet more stuff..

我找到了 pcregrep -n -M,我知道我可以使用 sed 和这个命令循环搜索每个段落,但是 pcregrep 并不是在每个系统上都有,所以如果可以避免它会很好。使用标准的 *nix 东西寻找优雅的东西,最好不要使用 perl。

* 一些不错的帖子和想法,但尽管在我发布的有限案例中确实有效,但它们并没有普遍发挥作用,因此我调整了示例数据,以便您查看它是否会更普遍

* 这是一个只打印多行段落的 sed 单行:

sed -e '/./{H;$!d;}' -e 'x;/.*\n.*\n.*/!d' file

【问题讨论】:

  • 我打印了错误的输出,但由于上次输出,它仍然无法正常工作,最新版本可以: awk -v RS= '{gsub(/[[:blank:]]+ $/,""); gsub(/[[:blank:]]+\n/,"\n")} !seen[$0]++{ORS=RT;print}' - 谢谢

标签: awk sed grep


【解决方案1】:

这主要是你想要的。唯一的问题(我知道的副手)是它将输入中的空白行折叠成输出中的单个空白行。

awk -v RS= '!x[$0]++{print; print ""}'

使用“如果 RS 设置为空字符串,则记录由空行分隔”这一事实。并为 awk 吞下的 RS 打印一个额外的空白行。

编辑:结合@EdMorton 的建议可以让你得到这个。

awk -v RS= -v ORS='\n\n' '!seen[$0]++'

awk -v RS= '!seen[$0]++{ORS=RT; print}' 让 GNU awk 使段落之间的间距与输入保持一致(而不是折叠空行)。

再次编辑:

这个版本似乎可以正常工作(使用 GNU awk 3.1.7 和更新版本,我不知道 3.1.6),但它在文件末尾添加了一个空行。

awk -v RS= '{gsub(/[[:blank:]]+$/,""); gsub(/[[:blank:]]+\n/,"\n")} !seen[$0]++{ORS=RT;print}'

【讨论】:

  • +1:您可以使用-vORS="\n\n" 而不是两个print 语句。虽然这可能只是一个偏好问题。
  • @jaypal 我没有想到这一点,但我没有想到printf "%s\n\n",$0,但认为使用它不值得改变。 ORS 虽然更干净。
  • 好主意,它适用于我发布的原始示例数据,但我正在寻找更通用的东西,我调整了示例数据。很抱歉,我一开始认为放这么长的样本数据很浪费空间。
  • @A.Danischewski 为什么more stuff ...yet more stuff.. 行会出现在您想要的输出中?是什么让它们与 this is a paragraph 不同?
  • 这是perl 等效项。 perl -00 -ne'$h{$_}++ or print' fileawk 也应该可以工作。您应该发布没有被 Etan 提供的脚本过滤的数据,否则我们都只是在浪费时间。
猜你喜欢
  • 2018-12-13
  • 1970-01-01
  • 1970-01-01
  • 2012-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-17
相关资源
最近更新 更多