Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question
    
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

3 Answers 3

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.

share|improve this answer
5  
Actually the typical awk code for such task is usually ls -l | awk 'NR==122,NR==129'. –  manatwork Sep 6 '13 at 9:06

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.

share|improve this answer

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

ls -l | tail -n +122 | head -n 8
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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