we all know that we can get the columns of a line using awk, but the columns is split by white spaces:

cat FileName | awk ' { print $1,$2,$3 .... }'

but what if we want to split the files according to '\n':
for example if we have this file:


and we want to get the second word 'Hello' using 'awk' what should we do?

  • @AvinashRaj , is replaced by (well more like the arguments to print are joined with) OFS, not FS. So it's {print $1 OFS $2 OFS $3} – Stéphane Chazelas May 28 '14 at 9:12

In awk, there are two main separators: the field separator, and the record separator. The record separator separates different groups of fields. As you can probably guess from this description, the default record is a newline. You can access the current record index in the variable NR.

awk 'NR==2 { print; exit }'

You can also just write awk NR==2, but awk will (since you didn't tell it to exit after finding it) loyally continue processing the rest of the file after it reaches line 2, which might take a long time in a large file. The exit tells awk to exit immediately after printing record 2.

  • From which file-size is the exit approach quicker, if you include the additional typing time? – Bernhard May 28 '14 at 7:36
  • 1
    @Bernhard That's too broad to be answered without knowledge of the processing speed, the speed at which awk reads, and, of course, the speed at which the user types. In general, my approach when answering questions is to make the solution generalisable for the most broad number of use cases, so long as it does not compromise readability or encumber function. After all, this site is supposed to provide an environment to help more than just the original question giver. :-) – Chris Down May 28 '14 at 7:41

Depending on what you are trying to do here, you might be able to use awk's "multi-line-record" mode. From Gawk's manual:

If RS is set to the null string, then records are separated by blank lines. When RS is set to the null string, the newline character always acts as a field separator, in addition to whatever value FS may have.

So in your case you could get the second line like this:

awk '{ print $2 }' RS= FileName



You could also use sed to print only the second line,

sed -n '2p' file


sed '2!d;q' file

for sed to quit after it has read and printed the second line so it doesn't read the rest of the file.


head -n 2 file | tail -n 1
  • 2
    We could make sed to quit after first match by specifying q flag. – Avinash Raj May 28 '14 at 7:47

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.