30

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. Commented Sep 6, 2013 at 19:45

3 Answers 3

54

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
  • 6
    Actually the typical awk code for such task is usually ls -l | awk 'NR==122,NR==129'. Commented Sep 6, 2013 at 9:06
  • what is the command for get last 100 line from the file using awk Commented Jan 2, 2019 at 13:22
  • @ShihabudheenKM May have a look at this: stackoverflow.com/questions/12546919/… Commented Jan 21, 2020 at 8:59
12

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.