Skip to content
Advertisement

Use awk to create file

I have a file that contain :

Mr Q
01629699998
Ms Nhung
011287633

I would like to use this awk '{print "BEGIN:VCARD";print "Name:"$0;print "TELEPHONE:"$0;print "END:VCARD"}' file to create this result

BEGIN:VCARD
Name: Mr Q
TELEPHONE:01629699998
END:VCARD
BEGIN:VCARD
Name: Ms Nhung
TELEPHONE:011287633
END:VCARD

But the code above does not get that,Anyone can help me ,thanks

Advertisement

Answer

Try:

$ awk '{if (NR%2) printf "BEGIN:VCARDnName: %sn",$0; else printf "TELEPHONE:%snEND:VCARDn",$0}' inputfile
BEGIN:VCARD
Name: Mr Q
TELEPHONE:01629699998
END:VCARD
BEGIN:VCARD
Name: Ms Nhung
TELEPHONE:011287633
END:VCARD

How it works

Your input file consists of pairs of lines. The first line has a name and the second a phone number. Thus, we want to do something different on odd numbered lines (name) and even numbered lines (phone).

  • if (NR%2)

    This begins an if statement with a test based on the line number modulo 2.

  • printf "BEGIN:VCARDnName: %sn",$0

    This is command executed for odd-numbered lines.

  • else printf "TELEPHONE:%snEND:VCARDn",$0

    This is what is executed for even-numbered lines.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement