【问题标题】:Grouping Regex Output According to Directory Name根据目录名称对正则表达式输出进行分组
【发布时间】:2017-10-20 00:48:24
【问题描述】:

我试图编写一个 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");

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

【问题讨论】:

  • 您想要的输出与您的示例输入不匹配。如果您使两者完全一致,您可能会得到更好的答案。
  • @John1024 不是吗?
  • 确实匹配。文件名和内容是为了引导人。
  • @123 字符串report_somedir1 出现在输出中,但不在输入中。字符串client.cpp 在输入中出现两次,但在输出中没有出现一次。
  • report_somedir1 是输出文件的示例名称。不是输出本身。由于我们按 somedir1 对它们进行了分组,并且 client.cpp 属于其他目录,因此我们在此输出中看不到它们。为什么人们不阅读@John1024就分享破坏性的cmets

标签: regex bash scripting grep


【解决方案1】:

试试这个:

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

【讨论】:

  • 感谢您的贡献。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-04
  • 2015-08-09
  • 1970-01-01
  • 1970-01-01
  • 2018-09-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多