28

I want to extract some lines with awk. Is it possible to do the following task:

ls -l | awk 'BEGIN FOR(i=122;i<=129;i++) FNR==i'

How can I display the details from line numbers 122 to 129?

1
  • 1
    If you were to do this in a loop, I'd suggest the sed method, since sed is so much smaller (and loads faster) than awk.
    – zrajm
    Sep 6, 2013 at 19:45

3 Answers 3

52

You have not understood how awk works. The "program" specified is always executed once for each line (or "record" in awk parlance) of input, there's no need for FOR or any similar construct. Just use:

verbose method

ls -l | awk 'NR>=122 && NR<=129 { print }'

more compact method

ls -l | awk 'NR==122,NR==129'

Ths one give a range for NR, which is the "Number Record", typically this is the current line awk is processing.

3
11

One more alternate method would be to use sed:

ls -l | sed -ne '122,129p'

But if, as your question suggests, it's important to use awk for this, go with manatwork's comment on Zrajm's answer. As awk's documentation states:

   A  pattern  may  consist  of two patterns separated by a comma; in this
   case, the action is performed for all lines from an occurrence  of  the
   first pattern though an occurrence of the second.

So if you want, you can also make more advanced conditions. For example:

ls -l | awk 'NR==122,/foobar/'

This would start output at line 122, and continue until a line contained the word "foobar".

If you tell us the actual use case, we might be able to help with answers that provide a better solution. I'm worried that this sounds like an XY problem.

4

Another way of doing this (though I prefer the awk method) using coreutils:

ls -l | tail -n +122 | head -n 8

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .