【问题标题】:Trying to remove repetitions in a paragraph using BASH尝试使用 BASH 删除段落中的重复项
【发布时间】:2020-11-27 18:23:01
【问题描述】:

您好,我正在编写一个简单的 BASH 来删除段落中由单个空格分隔的任何单词的连续重复出现,并将输出重定向到标准输出,这是我得到了多远。

文件1

**double double toil and trouble 
fire burn and cauldron bubble bubble 
tomorrow and tomorrow and tomorrow 
creeps in this this petty pace from day toto day**

echo `<file1` | sed -e 's/\b\([a-z ]\+\)\1/\1/g' | cat > file2

这是在一行中输出,如下所示。

double toil and trouble fire burn and cauldron bubble tomorrow and tomorrow creeps in this petty pace from day to day

并且遗漏了一些东西,因为它没有正确删除事件。

【问题讨论】:

  • 只要使用sed 's/\b\([a-z ]\+\)\1/\1/g' file &gt; file2
  • 问题是明天的第 3 行被删除,这是不正确的,因为在 'tomorrow' 之后有 'and' & 第 4 行 'toto' 被删除,它没有被空格分隔,所以不应该被认为是连续的重复。
  • 应用标签前请阅读标签说明。其中一半放错地方了!

标签: regex linux bash shell


【解决方案1】:

你可以使用

sed 's/\b\([a-z]\+\)\s\1\b/\1/g' file > file1
sed 's/\b\([a-z]\+\)[[:space:]]\1\b/\1/g' file > file1

请参阅online demo。正则表达式匹配

  • \b - 单词边界
  • \([a-z]\+\) - 第 1 组:任意一个或多个小写字母
  • [[:space:]] / \s - 一个空格
  • \1 - 与第 1 组中的值相同
  • \b - 单词边界。

【讨论】:

  • @Abelisto 是的,GNU sed 支持的I 将以不区分大小写的方式匹配。
  • 效果很好,感谢您的解释。如何将修改后的文本输出到标准输出而不是文件?
  • 我找到了,/dev/stdout
猜你喜欢
  • 2021-07-05
  • 2021-10-01
  • 2018-03-24
  • 1970-01-01
  • 2022-10-23
  • 2021-11-29
  • 1970-01-01
  • 1970-01-01
  • 2013-01-16
相关资源
最近更新 更多