help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] getline awk


From: Davide Brini
Subject: Re: [Help-bash] getline awk
Date: Sun, 20 Jan 2019 11:24:20 +0100

On Sat, 19 Jan 2019 19:16:33 +0100, Gérard ROBIN <address@hidden> wrote:

> Hello,
> getline is strange (in awk)
> 
> when I run this script:
> #-------------------------------- begin -----------------------------
> 1 #!/bin/bash
> 2
> 3 awk 'BEGIN { getline; print $1 ;getline; print $2}' fich2.txt
> #-------------------------------- end -------------------------------
> 
> cat fich2.txt
> 
> line1-field-1 line1-field-2 line1-field-3 line1-field-4 line1-field-5
> 
> line2-field-1 line2-field-2 line2-field-3 line2-field-4 line2-field-5
> 
> line3-field-1 line3-field-2 line3-field-3 line3-field-4 line2-field-5
> 
> line4-field-1 line4-field-2 line4-field-3 line4-field-4 line4-field-5
> 
> I get:
> 
> line1-field-1

You actually get an empty line after that.

> If I write the line 3 : 
> awk 'BEGIN { getline; print $1 ;getline; getline; print $2}' fich2.txt
> 
> I get: (as expected)
> 
> line1-field-1
> line2-field-2

The first getline reads the first line, whose first field is
"line1-field-1". The second getline reads the second line of the file, an
empty line (which you do nothing with). The third getline reads the third
line of the file, whose second field is "line2-field-2". 

 
> Now I run the script:
> 
> #---------------------------i--------- begin
> --------------------------------- #/bin/bash
> 
> ls -lSr --time-style=long-iso | awk 'BEGIN { getline; print; getline;
> print }' #-------------------------------------- end
> -----------------------------------
> 
> With:
> 
> ls -lSr --time-style=long-iso 
> 
> total 940
> -rw-r--r-- 1 user1 user1      0 2018-12-24 13:12 tmp1.txt
> -rw-r--r-- 1 user1 user1      3 2018-11-08 18:48 perslines
> ..........................................................
> ..........................................................
> 
> I get: (as expected)
> 
> total 940
> -rw-r--r-- 1 user1 user1      0 2018-12-24 13:12 tmp1.txt
> 
> in this case no need for two getline to have the expected result.
> 
> Why this difference in behavior of getline?

You have empty lines in your fich2.txt file, so the second "getline" is
reading an empty line. On the other hand, the output of "ls" has no empty
lines in it, so all getlines read a nonempty line.

-- 
D.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]