简体   繁体   English

在bash脚本中时如何使用Perl正则表达式字符?

[英]How can I use Perl regexp characters when inside a bash script?

I would like a command line function that I can run on any file to change the include("myinc.inc"); 我想要一个命令行函数,可以在任何文件上运行以更改include("myinc.inc"); PHP statement to include 'myfile.inc'; PHP语句include 'myfile.inc'; I have made a start by adding the following to my ~/.bashrc file: 首先,我在〜/ .bashrc文件中添加了以下内容:

function makestandard() {
    perl -p -i -e 's/include\("([\w\.]+)"\)/include '$1'/g' $*
}

I source ~/.bashrc; 我的source ~/.bashrc; and run the command at the command line as follows: 并在命令行上运行命令,如下所示:

$ makestandard myfile.php

I get myfile.php modified but instead of capturing the included file name, the included file name is corrupted to be the name of the current file. 我修改了myfile.php,但没有捕获包含的文件名,而是将包含的文件名损坏为当前文件的名称。 As a uninformed guess, I think the bash $1 variable is interfering with the $1 perl regexp variable. 作为一个不为人知的猜测,我认为bash $1变量正在干扰$1 perl regexp变量。

How can I fix this? 我怎样才能解决这个问题?


Background info ( no need to read ): We have started using PHP_CodeSniffer (phpcs) to sniff PHP code and report any bad "smells". 背景信息( 无需阅读 ):我们已经开始使用PHP_CodeSniffer(phpcs)来嗅探PHP代码并报告任何不良的“气味”。 Unfortunatly, phpcs doesn't fix the non-standard code, it only reports it. 不幸的是,phpcs不会修复非标准代码,它只会报告它。 Hence I would like to make a script that fixes some of the easy and common non-standard elements of our PHP code. 因此,我想制作一个脚本来修复我们PHP代码中一些简单且常见的非标准元素。 I plan to fill my makestandard bash function with a bunch of perl pie . 我计划用一堆perl饼来填充我的makestandard函数。

Shell environment: Whatever is out-of-the-box in Ubuntu 10.04. Shell环境:Ubuntu 10.04中现成的任何东西。

您应该转义简单的引号并删除最后一个括号:

perl -p -i -e "s/include\(\"([\w\.])+\"\)/include '\$1'/g" $*

它不是bash变量,而是单引号bash字符串中的单引号。

The original Perl statement, if it had worked, would have found 原始的Perl语句如果可行的话,将会发现

include("something.php") 

and written 并写成

include 'something.php')

that is, it would have removed the opening parenthesis and replace double quotes with single .. and not changed the extension as required. 也就是说,它将删除开头的括号并用单..替换双引号,并且不会按要求更改扩展名。

The following appears to work the way the OP intended: 以下内容似乎可以按照OP的预期方式工作:

function makestandard() {
    perl -p -i -e 's/include\("(\w+)\.inc"\)/include("$1.php")/g' $*
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM