2

I have multiple Key:Value pair data blocks separated by delimiter "*************" in an text file.The help required here is for a shell script to convert them into csv file.

*************
Name : Anderson 
Age : 32 
Country : U.S
*************
Name : Pramod 
Country : U.K
*************
Country : Africa 
Sport : Football
*************

The Output should be the csv file with below format OutPut :

Name,Age,Country,Sport
Anderson,32,U.S.A,
Pramod,,U.K,
,,Aftica,Football

This is kind of similar to rec2csv conversion from GNU recutils , but this I want it to get done by Shell Scripting

  • The Key:Value pairs are delimited by newline in same dataset. – Rudra Dec 3 '15 at 18:40
1

You can use awk for this conversion:

$ awk -F' : ' 'BEGIN { print "Name,Age,Country,Sport"; OFS="," }
    /^\*+$/ && NR>1 { print a["Name"], a["Age"], a["Country"], a["Sport"];
                      delete a; next}
    { a[$1]=$2} ' file.rec

Where : is used as input field seperator, , is set as output field seperator, the associative array a is used to temporarily store the values, the regular expresion ^\*+$ is used to recognize the record separating lines, a complete record is only printed after the second separating line (i.e. if number of records are greater than 1) and after each record the array is cleared.

The variables $1 and $2 reference the key and value in the input. The next statement directly advances the processing to the next line.

Not existing keys in the associative array result in empty strings - which matches the question.

  • Thanks Maxschlepzig for the the solution , it worked as expected. – Rudra Dec 6 '15 at 5:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.