如何匹配\ n \ n使用perl one liner?

时间:2016-04-11 17:05:58

标签: perl

我的示例文件:

As I Come Into Your Presence 
Key: F

1 As I come into Your presence
Past the gates of praise
Into Your sanctuary
Till we are standing face to face 
And look upon Your countenance
I see the fullness of Your glory
And I can only bow down and say 

Chorus:
Your awesome in this place
Mighty God
You are awesome in this place
Abba Father
You are worthy of all praise
To You our lives we raise
You are awesome in this place
Mighty God
    <--- Empty line here
    <--- Empty line here

我写了这个perl one-liner以在整个合唱块周围获得<i></i>个标签:

perl -p0e "s#Chorus:(.*?)\n\n#<i>Chorus:$1</i>#gsm" file

结果:

As I Come Into Your Presence 
Key: F

1 As I come into Your presence
Past the gates of praise
Into Your sanctuary
Till we are standing face to face 
And look upon Your countenance
I see the fullness of Your glory
And I can only bow down and say 

<i>Chorus:</i>% 

我无法获得所需的结果,</i>之后的整个合唱后将打印Mighty God标记。

错误在哪里?我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:2)

逃避$

perl -p0777e "s#Chorus:(.*?)\n\n#<i>Chorus:\$1</i>#gsm" file.

同样@Kenney在评论中提到:

Use single quotes on the commandline to wrap perl expressions otherwise the shell expansion will kick in.

答案 1 :(得分:2)

如果您只是将其用单引号而不是双引号,那么您的解决方案就可以正常工作。无论你运行什么语言/解释器,你都应该总是使用shell中单行的单引号来保持shell插值不会弄乱。

在您的代码中:

perl -p0e "s#Chorus:(.*?)\n\n#<i>Chorus:$1</i>#gsm" file

$1在它到达Perl之前被shell扩展,所以Perl看到了这个:

perl -p0e "s#Chorus:(.*?)\n\n#<i>Chorus:</i>#gsm" file

并愉快地删除你的合唱。如果您改为使用单引号:

perl -p0e 's#Chorus:(.*?)\n\n#<i>Chorus:$1</i>#gsm' file

它将按预期工作。

但请注意,-0表示任何蠕变到输入中的NUL字符仍然会导致Perl在该点将其拆分为多个记录。更正确的解决方案是使用-0777代替,它告诉Perl没有值应该分割输入;无论它包含哪些数据,它都被视为单个记录。

perl -p0777e 's#Chorus:(.*?)\n\n#<i>Chorus:$1</i>#gsm' file