Posts

Showing posts from 2024

From unique values of first column, get all the values of the 2nd column and print them in the same line by separating them with commas

The what: I have a file as below: $ cat sample.csv DEPT_ID,EMP_NAME 100,Keshava 100,Madhava 100,Narayana 100,Govinda 100,Vishnu 110,Madhusudana 110,Trivikrama 110,Vamana 110,Shridhara 110,Hrishikesha 110,Padmanabha 120,Damodara 120,Sankashana 120,Vasudeva 120,Pradyumna 130,Aniruddha 130,Purushottama 130,Adhokshaja 130,Narasimha 140,Achyuta 140,Janardana 140,Upendra 140,Hari 140,Krishna  The challenge is to make it look like below: $ cat sample.csv DEPT_ID: EMP_NAME (SEPARATED BY COMMA) 100: Keshava, Madhava, Narayana, Govinda, Vishnu 110: Madhusudana, Trivikrama, Vamana, Shridhara, Hrishikesha, Padmanabha 120: Damodara, Sankashana, Vasudeva, Pradyumna, Aniruddha 130: Purushottama, Adhokshaja, Narasimha 140: Achyuta, Janardana, Upendra, Hari, Krishna The How: Method 1 - Using pure shell commands tail -n +2 sample.csv | cut -d "," -f1 | sort -u | while read dept_id; do emp_names=$(grep "${dept_id}" sample.csv | cut -d "," -f2 | tr '\n' '