Sunday, October 30, 2022

[SOLVED] How to print group name once and members below the group name from multiple CSVs

Issue

The below is my code which pulls from multiple CSVs and prints the group name and its members that logged in.

cat *csv | awk '{print $3,$4}' > /output/userreport.txt
/> the issue is that it is printing out the group name multiple times

This is the current output example
John, Marketing
Bob, Marketing
Ron, Marketing
Todd, Finance
Tim, Finance

The desired output would be
Marketing
John
Bob
Ron

Finance
Todd
Tim


Solution

I would use GNU AWK for this task following way, let file.csv content be

A, B, John, Marketing
C, D, Bob, Marketing
E, F, Ron, Marketing
G, H, Todd, Finance
I, J, Tim, Finance

then

awk 'BEGIN{FS=", "}{if(group!=$4){group=$4;print $4};print $3}' file.csv

output

Marketing
John
Bob
Ron
Finance
Todd
Tim

Explanation: I instruct awk to treat space-comma as field separator (FS) then if group is different than last seen (or empty string if nothing was processed yet) print group name. For every line print content of 3rd column.

(tested in GNU Awk 5.0.1)



Answered By - Daweo
Answer Checked By - Candace Johnson (WPSolving Volunteer)