technerdius
technerdius

Reputation: 353

Print items from text file with \n delimiter to a CSV file

I have a file that has a few lines printed as follows:

               username: no_way
               EMAILID: [email protected]
               enc_username: DEFAULT
               MACHINE_CODE: 
               FIRSTNAME: John
               LASTNAME: Doe
               ACCOUNT_STATUS: Y

I want to capture username:, EMAILID:, FIRSTNAME: and LASTNAME: and print those in a CSV file that has:

no_way,[email protected],john,doe 

...on each row.

I tried using:

cat file | egrep 'ACCOUNT_STATUS:\ Y' &  egrep 'EMAILID:' & egrep 'username:' >> newfile

But, this doesn't work. I realized it is because the | pipe filters only that single line and since these are on separate lines, this will not work.

Then, I tried just changing the delimiters:

tr -dc '\n' ',' file | tee newfile

But, this gave me an error whether I used '-dc' or any options whatsoever.

What do I need to do to take these lines and put them in a CSV file?

I am using bash.

Upvotes: 1

Views: 34

Answers (1)

John1024
John1024

Reputation: 113834

Using awk

$ awk '$1 ~ /^(username:|EMAILID:|FIRSTNAME:)$/{printf "%s,",$2} $1 ~ /LASTNAME:/{print $2}' file
no_way,[email protected],John,Doe

How it works

  • $1 ~ /^(username:|EMAILID:|FIRSTNAME:)$/{printf "%s,",$2}

    If the first field matches one of username:, EMAILID:, or FIRSTNAME:, then print the second field followed by a comma.

  • $1 ~ /LASTNAME:/{print $2}'

    If the first field matches LASTNAME:, then print the second field followed by a newline.

Using bash

while read key value
do
    case "$key" in 
        username:|EMAILID:|FIRSTNAME:) printf "%s," "$value";;
        LASTNAME:) printf "%s\n" "$value";;
    esac
done <file

This produces the output:

no_way,[email protected],John,Doe

Upvotes: 1

Related Questions