【问题标题】:How to remove space (?) from empty line using perl?如何使用 perl 从空行中删除空格(?)?
【发布时间】:2016-04-05 15:59:02
【问题描述】:

我想从this file 中删除空行,以便歌曲的各节之间只有两个\n。第 7、8 和 20 行似乎有空格,但我猜它们不是常规空格,因为我无法通过使用 \s 的替换来删除它们。

文本复制如下(为清楚起见,空格标记为<-- HERE),但堆栈溢出编辑器似乎已将特殊空格更改为常规空格,因此您必须查看原始文件以进行复制我的问题。

9a I Believe in a Hill Called Mount Calvary

1 There are things, as we travel this earth's shifting sands,
That transcend all the reason
But the things that matter the most in this world,
They can never be held in our hand
 <-- HERE
 <-- HERE

Chorus
I believe in a hill called mount Calvary,
I believe whatever the cost!
And when time has surrendered and earth is no more
I'll still cling to that old rugged cross

2 I believe that the Christ who was slain on the cross,
Has the power to change lives today;
For He changed me completely a new life is mine
That is why by the cross I will stay
 <-- HERE

3 I believe that this life, with its great mysteries,
Surely someday will come to an end;
But faith will conquer the darkness and death
And will lead me at last to my Friend

我尝试了perl -pe 's/\n{3,}/\n\n/g',但没有成功,因为第 7、8 和 20 行有一些空间。

无论我尝试什么,我都无法删除空间。我尝试了以下命令:

  1. perl -p0e 's/\s{3,}/\n\n/g'
  2. perl -pe 's/^\s$//g'
  3. perl -pe 's/^ $//g'
  4. perl -pe 's/ $//g'

这些都不起作用。我想知道为什么会这样。会不会有一个non-space 字符充当空白?

我应该怎么做才能摆脱这个?

【问题讨论】:

    标签: regex perl


    【解决方案1】:

    我应该怎么做才能摆脱这个?

    如果您怀疑有趣的字符,请查看带有od -bc filename 的文件并查找异常字符。

    在删除&lt;-- HERE 标记后,我使用了您的文件,而您的第一个替代perl -p0e 's/\s{3,}/\n\n/g' file 工作正常。这是一个强有力的迹象(也就是证明 :-),这就是原因。

    【讨论】:

    • 是的,它们是不间断的空间。 OP 最初有一个指向他们文件的 pastebin 链接;我对其进行了编辑并在此处复制了内容,但显然 Stack Overflow 编辑器删除了不间断空格。对此感到抱歉。
    • 感谢您的精彩提示。第 7、8 和 20 行在上面一行显示值 302 240 012,在下面一行显示值 302 240 \n
    • 我发现这些是我从中提取这首歌的 Powerpoint 处理器引入的非 ascii 字符。我通过帖子here找到了解决方案
    【解决方案2】:

    正如我所观察到的,spaces 只是不可打印的字符。建议您尝试以下方法:

    perl -p0e 's/(?:[\x80-\xFF][\x0D\x0A]{2})+//g' 
    

    【讨论】:

    • 这不起作用。关于使用 od -bc filename 第 7、8 和 20 行在上面一行显示值 302 240 012,在下面一行显示值 302 240 \n
    • 那么在哪里下载原始文件的副本?不仅仅是从给定的链接复制/粘贴。
    • 您是否尝试过问题中给出的 pastebin 链接?我将粘贴的文件复制到 pastebin 中
    • 我做到了,但该模式对您不起作用。我只是想知道那些所谓的spaces 的十六进制值。
    • 很高兴知道您的问题已得到解决。我从链接下载了文件PCjDVh2p.txt,并提出了上述模式。
    【解决方案3】:

    感谢 Jens 使用od -bc filename 的建议,我找到了解决方案。

    转储显示字符 302 240 代替第 7、8 和 20 行的空格。

    在搜索八进制值的详细信息时,我从here 得到以下信息:

    man iso_8859-1 将 \240 标识为 NO-BREAK SPACE 和 \302 作为带有圆形的拉丁文大写字母 A

    我找到了如何从here 中删除字符。

    我曾经命令perl -pi -e 's/[^[:ascii:]]//g' filename纠正这个问题。

    感谢您提供的所有提示和付出的努力。

    【讨论】:

      【解决方案4】:

      我认为以下解决方案可以解决您的问题

      open FH,"/home/httpd/cgi-bin/space.txt";
      while(<FH>)
      {
      print if (!/^\s*$/) ;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-01-18
        • 2012-09-24
        • 2013-06-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多