Reputation: 35
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
Upvotes: 1
Views: 3400
Reputation: 20980
This is a pure bash option using printf
:
$ cat list_file # I have added one more entry for explanation.
Mr Q
01629699998
Ms Nhung
011287633
Dr. Drake Ramoray
0123456789
$ OLDIFS="$IFS" # save old IFS
$ IFS=$'\n' # Set IFS to newline, because the entries are newline separated.
$ printf 'BEGIN:VCARD\nName: %s\nTELEPHONE:%s\nEND:VCARD\n' $(<list_file)
BEGIN:VCARD
Name: Mr Q
TELEPHONE:01629699998
END:VCARD
BEGIN:VCARD
Name: Ms Nhung
TELEPHONE:011287633
END:VCARD
BEGIN:VCARD
Name: Dr. Drake Ramoray
TELEPHONE:0123456789
END:VCARD
$ IFS="$OLDIFS" # restore old IFS
Explanation:
IFS
). %s
entries. So, it divides 6 arguments into 3 group of 2 arguments. Upvotes: 0
Reputation: 113864
Try:
$ awk '{if (NR%2) printf "BEGIN:VCARD\nName: %s\n",$0; else printf "TELEPHONE:%s\nEND:VCARD\n",$0}' inputfile
BEGIN:VCARD
Name: Mr Q
TELEPHONE:01629699998
END:VCARD
BEGIN:VCARD
Name: Ms Nhung
TELEPHONE:011287633
END:VCARD
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:VCARD\nName: %s\n",$0
This is command executed for odd-numbered lines.
else printf "TELEPHONE:%s\nEND:VCARD\n",$0
This is what is executed for even-numbered lines.
Upvotes: 2