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 gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Parsing a file until given combination is reached. 2

Status
Not open for further replies.

Trevoke

Programmer
Jun 6, 2002
1,142
US
I have a file in the same format as the fortune cookie files
text
text
text
%
text
text
%
...

I am at the very beginning of my script; I need to parse through a certain amount of '%' and stop after the next one.
I'll need a special case if the counter is '0' to grab text until the first '%' but I'll try to take care of that on my own.

Assume the file I need to parse is called 'file' and the counter variable is called $count.

Also, I know that giving me the answer is the best solution, but if you give me a man page to browse, I might actually learn something.. And I can always come back if I don't get it :)

Thanks for your time.

-Haben sie fosforos?
-No tiengo caballero, but I have un briquet.
 
Hi

What do you want to do ? Extract one section, or split it in sections ?
Code:
[gray]# extract section 66 ( first section=0 )[/gray]
awk -v sec=66 '/%/{nr++} nr==sec,/%/{print}' fortunecookie.txt

[gray]# split up the file in separate one-cookie files[/gray]
csplit fortunecookie.txt '/%/' '{*}'
You did not mention what do you want to happen with the separators, so I just left them were they was.

Feherke.
 
Whoa.

I want to keep the file as it is, and simply extract one section, so your extraction code works beautifully.
However, I'd like to get rid of the '%' on either side..

And man awk is a little bit heavy for me to digest immediately. :)

Thanks a lot already!

-Haben sie fosforos?
-No tiengo caballero, but I have un briquet.
 
Hi

A quick solution is to just put another test with an [tt]if[/tt]. Also should be better to restrict the regular expression to match only lines with "%" alone :
Code:
awk -vsec=66 '/^%$/{nr++} nr==sec,/^%$/{if(!/^%$/)print}' fortunecookie.txt

Feherke.
 
That's amazing!
First of all - it greps (awks?) exactly what I need it to.. And then, even though there's no space between -v and sec=66, it still parses it properly!

I'm amazed and must now go and master this language.
Thank you!

-Haben sie fosforos?
-No tiengo caballero, but I have un briquet.
 
Hi

Trevoke said:
And then, even though there's no space between -v and sec=66, it still parses it properly!
Just to mention another nice behaviour of [tt]awk[/tt], if the variable setting is after the code, the -v is not needed at all :
Code:
awk '/^%$/{nr++} nr==sec,/^%$/{if(!/^%$/)print}' sec=66 fortunecookie.txt

Feherke.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top