Ram
Ram

Reputation: 39

Replacing new line with comma seperator

I have a text file that the records in the following format. Please note that there are no empty files within the Name, ID and Rank section.

"NAME","STUDENT1"
"ID","123"
"RANK","10"
"NAME","STUDENT2"
"ID","124"
"RANK","11"

I have to convert the above file to the below format

"STUDENT1","123","10"
"STUDENT2","124","11"

I understand that this can be achieved using shell script by reading the records and writing it to another output file. But can this can done using awk or sed ?

Upvotes: 0

Views: 57

Answers (5)

Ed Morton
Ed Morton

Reputation: 203522

$ awk -F, '{ORS=(NR%3?FS:RS); print $2}' file
"STUDENT1","123","10"
"STUDENT2","124","11"

Upvotes: 1

ctac_
ctac_

Reputation: 2471

With sed

sed -E 'N;N;;y/\n/ /;s/([^,]*)(,[^ ]*)/\2/g;s/,//' infile

Upvotes: 0

RavinderSingh13
RavinderSingh13

Reputation: 133518

Following awk may also help you on same.

awk -F, '{ORS=$0~/^"RANK/?"\n":FS;print $NF}'  Input_file

Upvotes: 0

choroba
choroba

Reputation: 241868

With awk, printing newline each 3 lines:

awk -F, '{printf "%s",$2;if (NR%3){printf ","}else{print""};}'

Upvotes: 0

hek2mgl
hek2mgl

Reputation: 157992

With awk:

awk -F, '$1=="\"RANK\""{print $2;next}{printf "%s,",$2}' file

Upvotes: 0

Related Questions