regex - 解析 git status 日志,如果修改的文件来自给定目录则退出

标签 regex shell perl

我编写了以下脚本,如果 git status 中修改的文件来自 directory_3,则会抛出错误。现在我想增强此脚本,以便在任何目录中修改文件时退出,除了: directory_1/path/to/dir_1/directory_2/path/to/dir_1/ 。 我无法编写脚本如何忽略如下所示的 git status 日志 (git_status.log ) 的前两行和后三行。我如何修改 if 条件 以忽略除上述两个目录之外的所有目录。

INITIAL_SCRIPT

#!/usr/bin/perl
use strict;
use warnings;

my $filename = "/home/user/git_status.log";
open(my $fh, '<:encoding(UTF-8)', $filename) or die "Could not open file '$filename' $!";

while (my $row = <$fh>) {
    chomp $row;
    #print "INFO: $row \n";

    if(grep(/\bdirectory_3\b/, $row))
    {
        print "INFO: This is an error case. Exit now \n";
        print ">>> $row \n";
        exit 1;
    }
}

INPUT_FILE

$> cat git_status.log

On branch development_branch
Changes to be committed:

    modified:   directory_1/path/to/dir_1/file1.txt
    modified:   directory_1/path/to/dir_2/file2.txt
    new file:   directory_2/path/to/dir_1/file3.txt
    modified:   directory_2/path/to/dir_2/file4.txt
    new file:   directory_3/path/to/dir_2/file5.txt
    modified:   directory_3/path/to/dir_2/file6.txt

It took 3.92 seconds to enumerate untracked files. 'status -uno'
may speed it up, but you have to be careful not to forget to add
new files yourself (see 'git help status').

最佳答案

您只需要增强正则表达式即可忽略这些行。您可以使用以下内容来识别以 modified:new file: 开头的行,以及那些不包含您所允许的路径的行假如。这样,如果正则表达式达到某些结果,则您的条件变为 true,并且您可以抛出错误,如 OP 中所示

if( grep { ( (/\b(modified|new file):/ ) and ( !/((directory_1|directory_2)\/path\/to\/dir_1)/) ) } $row )

为了在命令行上快速检查,您可以将状态输出通过管道传输到

,而不是将 git status 的结果转储到文件并稍后解析它
perl -le 'print grep{/\b(modified|new file):/ && !/((directory_1|directory_2)\/path\/to\/dir_1)/}<>'

关于regex - 解析 git status 日志,如果修改的文件来自给定目录则退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59098603/

相关文章:

regex - 消极回顾的替代方案?

python - 以数字 5 开头的正则表达式

bash - 如何等待消息出现在登录 shell 中

php - 通过 bash 在 linux 中生成一个完全独立的进程

perl - 如何使用 perl 在 Windows 10 上获取 OsVersion

regex - 范围> = 0但小于1000的正则表达式

javascript - 如何从 Javascript 中的字符串中获取占位符?

linux - 管理 Shell 任务

c - C shell 内的多个管道

mysql - 我是否需要为 DBIx::Class belongs_to 关系手动创建索引