Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Re-format file of stanza format

Status
Not open for further replies.

ranjit

Technical User
Apr 14, 2000
131
GB
I have a file with a stanza format which I'd like converted into a comma separated line format:

Input file:
ITEM: 0012345
COST: 750.00
QTY: 2
DESC: GARMENT

ITEM: 0099887
COST: 250.00
QTY: 5
DESC: FOOTWARE

ITEM: 5024655
COST: 50.00
QTY: 10
DESC: TIE

Desired output:
0012345, 750.00, 2, GARMENT
0099887, 250.00, 5, FOOTWARE
5024655, 50.00, 10, TIE

Any ideas?

Thanks
 
Try something like this:
Code:
awk -F: '
/^ITEM/,/^QTY/{printf "%s,",$2}
/^DESC/{printf "%s\n",$2}
' path/to/stanza >path/to/csv

Hope This Help
PH.
 
or

nawk -f stanza.awk stanza.txt

#--------------------- stanza.awk
BEGIN {
RS=""
OFS=","
}
{
for(i=2; i<= NF; i++)
printf(&quot;%s%s&quot;, !(i%2) ? substr($i,index($i, &quot;:&quot;)+1) : &quot;&quot;, (i%2) ? OFS : &quot;&quot;);

print &quot;&quot;;
}

vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
Thanks for the replies. Vlad - could you (or anyone) please explain how the printf statement works in the the above routine.

Thanks
 
The output could probably be simplified.

BEGIN {
# a 'record' is a block of lines separated by a 'blank' line
RS=&quot;&quot;

# the output field separator is ','
OFS=&quot;,&quot;
}

{
# iterate through the fields for a currect record
#starting with the the second fields
for(i=2; i<= NF; i++)
# for every field output 2 character strings
# 1-st char. string: '!(i%2) ? substr($i,index($i, &quot;:&quot;)+1) : &quot;&quot;,
# if the it's an EVEN [!(i%2)] field, output the
# substring of the field FOLLOWING the first ':'
# if it's an ODD field - output nothing
# 2-st char. string: '(i%2) ? OFS : &quot;&quot;'
# if it's an ODD field, output a field separator 'OFS=&quot;,&quot;'
# if it's an EVEN field, output nothing.
printf(&quot;%s%s&quot;, !(i%2) ? substr($i,index($i, &quot;:&quot;)+1) : &quot;&quot;, (i%2) ? OFS : &quot;&quot;);

print &quot;&quot;;
};

vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top