1

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.

  • What is with the other lines? Should they be printed too, or only line 5 and then 2 and 3? – chaos Jan 8 '16 at 8:41
  • yes other lines should follow through. – asadz Jan 8 '16 at 8:42
3

One way:

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

Try:

$ 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
    print l2
    print l3
    next
  }
  1                          # Print other lines
' <file

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

  • excellent, may i know at the END why print l2 and l3 again? – asadz Jan 8 '16 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 '16 at 8:56
  • Thank you, I've used it in a loop, to move the 1st line after the 6th (lines 1,7,13,19...): awk '(FNR%6) == 1 {l = $0; next} (FNR%6) == 0 {print; print l; next} 1' – parameciostudio Aug 13 at 9:31
3
awk 'NR == 2 || NR == 3 {l = l RS $0; next}
     NR == 5 {$0 = $0 l}
     {print}'
2

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.
  • Thanks, but did you run this cmd? I don't think it delivers the right results – asadz Jan 8 '16 at 8:48
  • Note that for (i in a) returned in unspecified order, so line 2 can become after line3. – cuonglm Jan 8 '16 at 8:49
  • @asadz I corrected the command – chaos Jan 8 '16 at 13:21

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.