Initially I got the solution already in this post.
However those are only for 2 patterns. It turns out I need more than 2 patterns now, possibly the 3rd pattern and even 4th pattern.
I tried using the following solution by adding more patterns that I got from @cas
awk -v OFS=, '
match($0,/\<[[:digit:]]{1,2}\/[[:digit:]]{1,2}\/[[:digit:]]{4} [[:digit:]]{1,2}:[[:digit:]]{1,2}\>/,a) {dt = a[0]; next};
match($0,/3rd pattern/,b);
match($0,/INC-[[:digit:]]+-[[:digit:]]+/,a) {print a[0], dt; print b[0]}' filename.log
and I'm getting the following output:
INC-210305-00000426,3/6/2021 5:19
INC-20210304-00006690,3/5/2021 5:24
only adding more space. Any other suggestion how I can grep for the 3rd or 4th pattern? they are indeed located in the different lines. Below is the input:
unwantedtext unwantedtext unwantedtext unwantedtext 8/1/2022 6:15 (1st Pattern)
unwantedtext unwantedtext unwantedtext unwantedtext
unwantedtext unwantedtext Report_A (3rd Pattern)
unwantedtext unwantedtext INC-220721-00007628 (2nd required pattern)
unwantedtext unwantedtext unwantedtext unwantedtext
unwantedtext unwantedtext Report_B (4th) Pattern)
The desired output is as follows:
INC-220721-00007628, 8/1/2022 6:15, Report_A
And later I might need the following output as well:
INC-220721-00007628, 8/1/2022 6:15, Report_A, Report_B
I'm using Cygwin and CentOS 7 environments.
Thank you in advance for the helpful solution.
a
and (if the match was successful) store the first element ofa
into another variable (dt = a[0]; next
) for use in the print statement later? Then notice how with the "third pattern" you added, you're NOT doing that. There's a reason why I used another variable - because every timematch()
is run, it overwrites the array (a
orb
) whether there were any matches or not....so the array doesn't survive past the current input line.END { }
block), iterate over the hash and print it.match($0,/3rd pattern/,b)
is run, which will be the next time an input line is read (the awk code is executed, in order, for each input line). that's why i said copy b[0] to another variable.