简体   繁体   中英

Grouping Regex Output According to Directory Name

I was trying to write a bash script in order to apply regex on this file.

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");

However, I cannot manage to collect the directory names as variable.

Last stable regex material I have is:

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

My goal is to group the entries that share the same parent directory in same file. For instance;

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");

What is the correct way to store the first pattern as a variable? Thank you in advance, for your time and patience.

Try this:

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

The above command will result in the creation of three files:

$ 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");

And:

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

And:

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

How it works

  • -F/

    This sets the field divider to / . In this way, the first field will be the directory.

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

    If the first field of the current line differs from the previous, then close the old file, update the variable d and create a new filename f .

  • print >>f

    Print the current line to file f .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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