awk not generating the expected output

Hi,

I am presently stuck in a csv file.

 
INPUT CSV
 
baseball,NULL,8798765,Most played
baseball,NULL,8928192,Most played
baseball,NULL,5678945,Most played
cricket,NOTNULL,125782,Usually played
cricket,NOTNULL,678921,Usually played

EXPECTED OUTPUT CSV
 
baseball,NULL,8798765,Most played 
           NULL,8928192,Most played   
           NULL,8928231,Most played  
cricket,NOTNULL,125782,Usually played
         NOTNULL,678921,Usually played

I am using the below code in input csv

 
awk -F"," '{if (NR>1 && a==$1) {print FS$2FS$3;a=$1}  else {print $0;a=$1}}' input.csv > output.csv

But I am getting the below output:-

 
baseball,NULL,8798765,Most played 
              8928192   
              8928231
cricket,NOTNULL,125782,Usually played
                678921

The code is deleting the duplicate items in 2nd column and third columns also...I want that the unique elements of the first column should be displayed but all other things for other columns should remain intact

Can somebody please help me...

awk  'BEGIN{FS=OFS=","}!a[$1] {print;a[$1]++;next}{print "\t"$2,$3,$4}' infile

baseball,NULL,8798765,Most played
        NULL,8928192,Most played
        NULL,5678945,Most played
cricket,NOTNULL,125782,Usually played
        NOTNULL,678921,Usually played

Hi,
It is giving the below error:-
awk 'BEGIN{FS=OFS=","}!a[$1] {print;a[$1]++;next}{print "\t"$2,$3,$4}' input.csv

awk: syntax error near line 1
awk: bailing out near line 1

Use nawk or /usr/xpg4/bin/awk on Solaris.

It worked...
Thanks very much..
Can you please explain it, so that it can be useful to me...
and also I can make some modification if it is necessary...

Ok, I'll explain the code of rdcwayx.

BEGIN{FS=OFS=","}

Set fieldseparators

!a[$1] {print;a[$1]++;next}

If the 1st field doesn't exist as an index of array a:

  • print the whole line
  • create a new element with the new index (1st field)
  • increase the value
  • get the next line.
{print "\t"$2,$3,$4}

This line should be run if the first field exists as an index in array a.
Print a tab and the fields 2, 3 and 4

1 Like

Thanks for the explanation Franklin.It was really of great help

From the last two days, I am seeing you guys are solving the issues like any thing else. I am overwhelmed by the quick and thorough response.
How can you do that ?
You don't know, how helpful you guys are to many of us.

Once again thanks very much. Looking for your support in future.

And also let me know how to give thanks, so that it comes in the profile of the solution provider...

The simplest way is to click the "Thank" icon on the reply who you want to thank

1 Like