Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have file content as:

this line 1 no un1x
this lines 22 0
butbutbut this 33 22 has unix
but not 1
THIS is not
butbutbut ffff
second line

awk 'NR==2 && NR==3 {f=$0;next}  NR ==5 &&f{print;print f}' awk.write

The problem here that in f I can only save value of nr==3 I want to move the lines 2 and 3 after line 5.

share|improve this question
What is with the other lines? Should they be printed too, or only line 5 and then 2 and 3? – chaos Jan 8 at 8:41
yes other lines should follow through. – asadz Jan 8 at 8:42
up vote 3 down vote accepted

One way:

awk 'NR==2 || NR==3{a[i++]=$0;next}1;NR==5{for(j=0;j<2;j++){print a[j];}}' file
share|improve this answer


$ awk '
  FNR == 2 { l2 = $0; next } # Save 2nd line
  FNR == 3 { l3 = $0; next } # Save 3rd line
  FNR == 5 {                 # Print 5th line, follow 2nd, 3rd
    print l2
    print l3
  1                          # Print other lines
' <file

Note that if you will lose the 2nd and 3rd line if the file had less than five lines.

share|improve this answer
excellent, may i know at the END why print l2 and l3 again? – asadz Jan 8 at 8:54
@asadz: Just want to handle the case where file is less than five lines, but the solution will be complex. Added a note. – cuonglm Jan 8 at 8:56
awk 'NR == 2 || NR == 3 {l = l RS $0; next}
     NR == 5 {$0 = $0 l}
share|improve this answer

You need multiple variables or an array. With awk:

awk 'NR==2||NR==3{a[i++]=$0;next} NR==5{print;for(c=0;c<i;c++){print a[c]}next}1' file

  • NR==2||NR==3 if it's line 2 or line 3
    • a[i++]=$0;next fill array a and continue.
  • NR==5 if it's line 5
    • print first print the line.
    • for(c=0;c<i;c++){print a[c]} loop trough the array and print its contents.
  • 1 is a true condition to print each line.
share|improve this answer
Thanks, but did you run this cmd? I don't think it delivers the right results – asadz Jan 8 at 8:48
Note that for (i in a) returned in unspecified order, so line 2 can become after line3. – cuonglm Jan 8 at 8:49
@asadz I corrected the command – chaos Jan 8 at 13:21

Your Answer


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.