I have a simple question, which is almost too simple to find on this forum or on awk learning sites.
I have some awk code that matches a line beginning with a number, and prints the 6th column of that line:
/^[1-9]/ {
print $6
}
How do I tell it to print only the first 50 rows of the column from the match?
ADDITIONAL QUESTION
I tried used my own version of the answers below and I got it to print 50 lines. However, now I am trying to choose which 50 lines I print. I do this by skipping a line that starts with a number and contains the word ‘residue’. Then I skip 5 lines that start with a number and contain a ‘w’. This method is working as if I am only skipping the line with residue and prints from the first line starting with a number after that. Do you know why my ‘w’s are not being considered.
#!/usr/bin/awk -f
BEGIN {
line = 0;
skipW = 0;
}
# Ignore all lines beginning with a number until I find one I'm interested in.
/^[0-9]+ residue/ { next }
# Ignore the first five lines beginning with a number followed by a 'w'.
/^[0-9]+ w/ {
skipW += 1;
if (skipW <= 5) next
}
# For all other lines beginning with a number, perform the following. If we are
# "printing", increment the line count. When we've printed 50 lines turn off
# printing from that point on.
/^[0-9]+/ {
++line
if ((line > 0) && (line <= 50)) print $6
}
This increments
num_printedeach time a match is found and prints out the first 50 such lines, regardless of where the lines are in the files in the input.This reads through all the input. If an early exit is OK, then you can use:
Note the switch from post-increment to pre-increment.