如何使用perl从空行中删除空格(?)?

时间:2016-04-05 15:59:02

标签: regex perl

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

下面再现了文本(为了清楚起见,标有<-- HERE的空格),但Stack Overflow编辑器似乎已将特殊空格更改为常规空格,因此您必须查看原始文件复制我的问题。

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'
  5. 这些都不起作用。我想知道为什么会这样。可能有一个non-space字符作为空白吗?

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

4 个答案:

答案 0 :(得分:1)

  

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

如果您怀疑有趣的人物,请使用od -bc filename查看该文件并查找不寻常的字符。

我删除了<-- HERE标记后使用了您的文件,而您的第一个替代perl -p0e 's/\s{3,}/\n\n/g' file工作得很好。这是一个强烈的迹象(又名证明:-),这就是原因。

答案 1 :(得分:1)

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

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

答案 2 :(得分:0)

由于Jens建议使用od -bc filename,我找到了解决方案。

转储在第7,8和20行的空格位置显示了字符302 240

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

  

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

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

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

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

答案 3 :(得分:-1)

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

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