根据目录名称对正则表达式输出进行分组



我试图编写一个bash脚本,以便在此文件上应用正则表达式。

somedir1/include/log.h:65:inline void ERROR(int, const std::string&)      {}
somedir1/common/packet.cpp:68:        ERROR(1, "File couldn't be opened");
anotherdir2/core/client.cpp:380:    ERROR(error, "Connection error");
otherdir3/src/client.cpp:534:            ERROR(1, "Wrong command");

但是,我无法设法将目录名称收集为变量。

我拥有的最后一个稳定的正则表达式材料是:

 [^,]*/[^,]*:[0-9]*:[^,].*n
#[^,]--->This one is the one I am interested in.

我的目标是将共享同一父目录的条目分组到同一文件中。例如;

fileName:   report_somedir1 
content:    somedir1/include/log.h:65:inline void ERROR(int, const std::string&)      {}
content:    somedir1/common/packet.cpp:68:        ERROR(1, "File couldn't be opened");

将第一个模式存储为变量的正确方法是什么?提前感谢您的时间和耐心。

试试这个:

awk -F/ '$1 != d{close(f); d=$1; f="report_"d} {print >>f}' file

上述命令将导致创建三个文件:

$ cat report_somedir1 
somedir1/include/log.h:65:inline void ERROR(int, const std::string&)      {}
somedir1/common/packet.cpp:68:        ERROR(1, "File couldn't be opened");

和:

$ cat report_anotherdir2 
anotherdir2/core/client.cpp:380:    ERROR(error, "Connection error");

和:

$ cat report_otherdir3
otherdir3/src/client.cpp:534:            ERROR(1, "Wrong command");

工作原理

  • -F/

    这会将字段分隔符设置为 / 。 这样,第一个字段将是目录。

  • $1 != d{close(f); d=$1; f="report_"d}

    如果当前行的第一个字段与上一个字段不同,则关闭旧文件,更新变量d并创建一个新的文件名f

  • print >>f

    将当前行打印到文件f

最新更新