【问题标题】:Removing all single letters from a textfile with SED使用 SED 从文本文件中删除所有单个字母
【发布时间】:2023-04-03 00:13:01
【问题描述】:

我想在 Linux 中使用 SED 命令从文本文件中删除所有包含一个字母的单词。比如我有文字:

yes said holmes answering the look rather than the words it is
so i know all about mccarthy
the old man sank his face in his hands god help me he cried but
i would not have let the young man come to harm i give you my word
that i would have spoken out if it went against him at the assizes
i am glad to hear you say so said holmes gravely
i would have spoken now had it not been for my dear girl it would
break her heartit will break her heart when she hears that i am
arrested

使用正则表达式,我使用 SED 命令如下:

sed -E 's/(\s[a-z]\s)/ /g' examplefile > destinationfile

我运行命令后,结果看起来和以前一样,没有任何变化。我错过了什么?

【问题讨论】:

  • 好吧,你只删除了一个字母的单词,所以输出会类似,见ideone.com/tSMtdY。反正输出和输入是不一样的。
  • 请将该示例输入的所需输出(无描述)添加到您的问题(无评论)。

标签: regex sed terminal


【解决方案1】:

这可能对你有用(GNU sed):

sed -E ':a;s/(^|\s)[a-z](\s|$)/\1/Ig;ta' file

删除行首、中行或行尾的任何单个字符,并将其替换为之前的空格(或缺少空格)。

【讨论】:

    【解决方案2】:

    可能您的根本问题是您的sed 不理解Perl 扩展\s

    另一个问题是匹配“ex a b c”中“a”周围的两个空格将“消耗”它们,从而无法匹配“b”。如果 "c" 在行尾,它后面没有空格,所以也不匹配。

    如果您的sed 支持单词边界\b,请尝试。它匹配一个空字符串,但仅在其一侧只有字母字符的位置匹配。

    sed 's/\b[a-z]\b//g'
    

    这将留下两个空格,其中一个已删除的单词被两边的空格包围;有多种方法可以解决此问题,但从您的要求中不清楚这是否有必要。

    【讨论】:

      【解决方案3】:

      https://regex101.com/r/VsQNjj/1

      使用\b 而不是\s

      \s 匹配空格。 \b 匹配单词边界。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-19
        • 2012-05-25
        • 1970-01-01
        • 2013-10-24
        相关资源
        最近更新 更多