Bash / Perl多行正则表达式问题

时间:2019-03-04 18:51:33

标签: regex bash perl

尝试在bash脚本中应用某些格式的文件,经过大量的网络搜索和试验/错误之后,我想使用perl regexes来实现这一点,因为我需要它与Mac / Linux兼容:

#!/bin/sh
FILES="$(find . -type f -name '*.php')"
for FILE in $FILES
do
    # 1. Add blank line after "global $XYZ" calls
    RET=$(perl -i -pe 's/^(\s*)global(\s)(.+);(\s*)$/$1global$2$3;\n\n\n/' $FILE)

    # 2. Add blank line before "$query" calls
    RET=$(perl -i -pe 's/\$query(\s+)(\.?=)/\$query $2/' $FILE)
    RET=$(perl -i -pe 's/^(\s*)\$query (\.?=)/\n$1\$query $2/' $FILE)

    # 3. Add blank line before "$ret" calls
    RET=$(perl -i -pe 's/\$ret(\s+)=/\$ret =/' $FILE)
    RET=$(perl -i -pe 's/^(\s*)\$ret =/\n$1\$ret =/' $FILE)

    # 4. Add blank line after single line "$ret" calls
    RET=$(perl -i -pe 's/^(\s*)\$ret(.+);(\s*)$/$1\$ret$2;\n/' $FILE)

    # 5. Add blank line before "list" calls
    RET=$(perl -i -pe 's/^(\s*)list\(/\n$1list(/' $FILE)

    # 6. Add blank line after single line "list" calls
    RET=$(perl -i -pe 's/^(\s*)list(.+);(\s*)$/$1list$2;\n/' $FILE)

    # 7. Add blank line after closing braces
    RET=$(perl -i -pe 's/^(\s*)\}(\s*)$/$1\}$2\n/' $FILE)

    # 8. Add blank line after closing multiline statements
    RET=$(perl -i -pe 's/^(\s*)\);(\s*)$/$1\);$2\n/' $FILE)

    # 9. Remove superflous blank lines
    RET=$(perl -i -0pe 's/(\n\s*){2,}(\n\s*)/\n$2/gs' $FILE)
    RET=$(perl -i -0pe 's/(\s*)(\/\/.+)(\n\s*){2,}$/$1$2\n/gs' $FILE)
done

虽然我已经使用在线正则表达式测试器对其进行了测试并且与之匹配,但它似乎通常可以正常工作,但最后一个正则表达式似乎没有发挥作用。

我怀疑它可能与上次运行中的/ g修饰符有关,但不确定。

基本上,我想在单行注释后修复空白行的实例,以便...

  // Some Comment

  $ret = "XYZ";

显示为...

  // Some Comment
  $ret = "XYZ";

正如所说的,整个事情就像正则表达式不存在一样。

1 个答案:

答案 0 :(得分:4)

以下是如何将脚本作为单个perl脚本编写的示例:

use strict;
use warnings;
use File::Find::Rule;

my @files = File::Find::Rule->new->file->name('*.php')->in('.');
@ARGV = @files;
$^I = '.bak';  # suffix of backup file, see perldoc perlvar
while (<<>>) {
    s/^(\s*)global(\s)(.+);(\s*)$/$1global$2$3;\n\n\n/;
    s/\$query(\s+)(\.?=)/\$query $2/;
    s/^(\s*)\$query (\.?=)/\n$1\$query $2/;
    s/\$ret(\s+)=/\$ret =/;
    s/^(\s*)\$ret =/\n$1\$ret =/;
    s/^(\s*)\$ret(.+);(\s*)$/$1\$ret$2;\n/;
    s/^(\s*)list\(/\n$1list(/;
    s/^(\s*)list(.+);(\s*)$/$1list$2;\n/;
    s/^(\s*)\}(\s*)$/$1\}$2\n/;
    s/^(\s*)\);(\s*)$/$1\);$2\n/;
    print;
}
@ARGV = @files;
local $/ = undef; # Read the whole file
while (<<>>) {
    s/(\n\s*){2,}(\n\s*)/\n$2/gs;
    s/^(\s*)(\/\/.+?)(\n\s*){2,}/$1$2\n/gs;
    print;
}