UNIX & GNU/Linux - awk - Using getline to retrieve data

We've already played with awk, passing it a file, but we're going now to see how to retrieve data from the user with the command line.

We would like to know what's the name of the user.

Let's ask him.


The -f flag is normally to tell awk that we're going to pass a file as argument. But if we don't, the shell will wait for a file.
Instead of a file, we will give to awk a string that we'll retrieve thanks to the getline function.

We could notice that all the code is inside the BEGIN pattern because there is only one line to analyse.

At line 7, we're going to retrieve the name's user with:

getline name < "-";

In this snippet we tell to getline to retrieve data from the user, putting this in the "-" character and then to put this into the name variable.
We need these two steps to retrieve data with getline.

Once retrieved, we can check is the user entered a name or if he didn't.
If he did, we print it, otherwise we use the UNKNOWN name.

We also retrieve the current date with:

"date" | getline;

Once retrieved, we can use columns of date we want.
Indeed, the full date is something like that:

Sat Oct 27 11:32:04 CEST 2012

So if we want to display, just "Sat", we have to use the $1 variable.
For 2012, it's $6, because this is the sixth element of date.




# Begin
    FS=" ";
    print "Hello, what is your name?";
    getline name < "-";
    if (name == "") {
        name = "UNKNOWN";
  "date" | getline;
  myDate  = $3 " " $2 " " $6;
    myHour = substr($4, 1, 5);
    print "On " myDate " at " myHour " I saw you, " name "!";

# Dev

# End
END {}


awk -f bp5.awk


Hello, what is your name?
On 27 Oct 2012 at 11:35 I saw you, Mi-K!


We can now easily retrieve data with getline.
Well done, you've made it. smiley

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Refresh Type the characters you see in this picture. Type the characters you see in the picture; if you can't read them, submit the form and a new image will be generated. Not case sensitive.  Switch to audio verification.