-1

I'm using

awk 'BEGIN {while((getline gf < "awk.script") > 0) {print gf}}' 

to read me first 3 three lines of the pattern. I can do with head -3 . But I don't want to since, I have to switch lines between two files.

Suppose awk.script contains

line 1
line 2
line 3 <------- until here
line 4 

I have tried updating the original cmd with this

 awk 'BEGIN {while((getline gf < "awk.script") > 0) && f{print $gf;f=0};NR<=3{f=1}}'

the code is influenced from the examples give on link:- https://stackoverflow.com/questions/17908555/printing-with-sed-or-awk-a-line-following-a-matching-pattern

error i'm getting is

awk: cmd. line:1: BEGIN {while((getline gf < "awk.script") > 0) f{print $gf;f=0};NR<=3{f=1}}
awk: cmd. line:1:                                                ^ syntax error
awk: cmd. line:1: BEGIN {while((getline gf < "awk.script") > 0) f{print $gf;f=0};NR<=3{f=1}}
awk: cmd. line:1:

How can it be done? thanks

2

You don't need to use getline, but if that is what you need:

echo|awk 'BEGIN {while((getline gf < "awk.script") > 0) {print gf; if(++i > 2) break;}}'

You could get the same behaviour like this:

awk 'NR>3{exit} {print $0}' input.txt

In yout attempt, two things were wrong: NR does not get incremented with getline, and the and operator && should not be used between the while clause and its code block. Your checking of f does not look appropriated.

  • thanks a lot can you explain use of ++i >2. – asad Dec 29 '15 at 16:48
  • In awk, variables are initialized with zero, so ++i will increment a variable (which at first does not exist, so it is zero), and in every loop of the while, i will get incremented, till it reaches 3, then it breaks the loop. – Kira Dec 29 '15 at 17:05

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.