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?

  • 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 '13 at 19:45

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.


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.


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

ls -l | tail -n +122 | head -n 8
 awk  'NR == 122,NR == 129{print $0}'  file

Here we can extract the lines from 122 to 129 of file.

$0 is used to print the whole file data between 122 and 129 lines.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.