Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
Hi there,
I trying to do some basic stuff with shell scripting and awk in cygwin. My main goal is actually to parse a textfile and check the source depot for changes and provide a report.
But baby steps first. From the various posts I read. I've used the following nifty function to print out the contents of a textfile.
#!/bin/sh
gawk '{while (getline 0)
{
print $0
}
exit
}'When I run this snippet I notice before it starts looping and displaying my textfile it will sit and wait for a CR.
What am I missing?. How come getline isn't just going straight into processing the textfile?
cheers,
ET

awk does the getlines (into $0 buffer) for you automatically. A basic awk solution will not use an explicit getline, but getline comes in very handy in many cases.
So we let awk read the lines. We specify line selection criteria and what to do when we find those lines. Let's say we have a file named myfile containging 6 lines. To print all lines (like the cat command):
awk '{print}' myfile
line A
So this guy walks
line B
into a bar with a
line C
duck under his arm ...Now find lines that start with "line" and print them:
awk '/^line/ {print}' myfile
line A
line B
line CAnd if what you want to do for each qualifying line (an action statement in braces) is simply "print", you can omit that because that is the default action:
awk '/^line/' myfile
line A
line B
line CBut if you want to do something other than print the entire line, such as print the second word, then:
awk '/^line/ {print $2}' myfile
A
B
CBut say we want to print the lines that follow each line that begins with "line". In this case, since I know my data, I could cheat and print only those lines that have more than two fields ('NF>2'), but the sure way to get them is: each time we find a line begninning with "line", do an explicit read of the next line and print it:
awk '/^line/ {getline;print}' myfile
So this guy walks
into a bar with a
duck under his arm ...Consider this program:
awk '{getline;print}' myfile
awk presents the first line, and we are saying "get the next line and print". Then awk automatically reads the next (3rd) line, and we say "get the next line and print". Therefore, the above program will print the 2nd, 4th, 6th, etc lines.
getline can also read lines from a file other than the main file being processed by awk, and in this case, it would be appropriate to have that in a while-getline loop.

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |