Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get the user input in awk

Tags:

awk

Is there any way to read the user input through the awk programming? I try writing a script to read a file which contained student's name and ID. I have to get the name of the student from the user through the keyboard and return all student's results by using the awk.

like image 230
femchi Avatar asked Oct 16 '12 03:10

femchi


2 Answers

I've tested with line

"awk 'BEGIN{printf "enter:";getline name<"/dev/tty"} {print $0} END{printf "[%s]", name}' < /etc/passwd" 

and for me is better solution and more readeable.

like image 93
MarianoVolker Avatar answered Sep 23 '22 15:09

MarianoVolker


You can collect user input using the getline function. Make sure to set this in the BEGIN block. Here's the contents of script.awk:

BEGIN {
    printf "Enter the student's name: "
    getline name < "-"
}

$2 == name {
    print
}

Here's an example file with ID's, names, and results:

1 jonathan good
2 jane bad
3 steve evil
4 mike nice

Run like:

awk -f ./script.awk file.txt
like image 23
Steve Avatar answered Sep 20 '22 15:09

Steve