Showing results for 
Search instead for 
Do you mean 

Script Help

Occasional Advisor

Script Help

Need help with pattern matching reading from a file. Trying to use egrep but not sure that is the best option.

File contents:

Register 6
CASH 100.00
CHECK 50.00
Register 6
.....other stuff
Register 7
CASH 2000.00
CHECK 10.00
Register 7
.....other stuff, etc.

I need my output to be
Register 6
CASH 100.00
CHECK 50.00

Register 7
CASH 2000.00
CHECK 10.00

Any advice on the best utility to use?
6 REPLIES
Highlighted
Honored Contributor [Founder]

Re: Script Help

grep -i -e "^register" -e "^cash" -e "^check" FILENAME

live free or die
harry d brown jr
Live Free or Die
Honored Contributor [Founder]

Re: Script Help

So I'm assuming that you only want to print a register name when you get to a cash and check line.

Create a script in a file called useme.awk :

/^Register/ {dareg=$0}
/CASH/ {dacash=$0}
/CHECK/ {print dareg; print dacash; print $0}

Run the script like this:

awk -f useme.awk < inputfile > outputfile

Best regards,

Kent M. Ostby
"Well, actually, she is a rocket scientist" -- Steve Martin in "Roxanne"
Honored Contributor [Founder]

Re: Script Help

Shannon,

Are you trying to display the sum of the amounts (cash or check) at the different registers? I'm not sure from your posting; could you clarify.

cheers!

Occasional Advisor

Re: Script Help

Actually I am not trying to display the sum necessarily but just the register number
and the cash and check amounts under the register number. The register numbers are listed twice in the file as well as some other garbage that i don't need. So I want the output to be something like

Register 6
CASH 100.00
CHECK 50.00

Register 7
CASH 2000.00
CHECK 10.00

With the register number and then the corresponding cash and check amounts.

Thanks for any help. I tried the other two suggestions. Couldn't get the grep to work and the awk script did not print register numbers but only amounts.
Honored Contributor [Founder]

Re: Script Help

That's odd, Kent's awk should work just fine. Here it is as a one-liner:

awk '/^Register/{dareg=$0}/CASH/{dacash=$0}/CHECK/{print dareg;print dacash;print $0}' < file

One long-haired git at your service...
Honored Contributor [Founder]

Re: Script Help

You can get with awk one liner as,

# awk '{ if ( $1 == "Register") { ln1=$0;getline ln2; split(ln2,a," ");if (a[1]=="CASH") { getline ln3; split(ln3,b," ");if (b[1]=="CHECK") { print ln1"\n"ln2"\n"ln3}}} print "\n";}'

hth.
Easy to suggest when don't know about the problem!