Pattern search the user input in a file in Unix using awk

0

I am trying to write awk script to search for a pattern that is given input by user, in a file.
My code look like this:
awk 'BEGIN{printf "Enter : ";getline input<"/dev/tty"} /'"$input"'/ {print}' <abc.txt
What I get as an output is the whole file. Can someone help me to find where I'm going wrong ?

learner1

Posted 2016-05-02T11:44:52.660

Reputation: 155

Answers

1

What you do is: you read the pattern from tty, you place it into a variable of awk (not of the shell) called input, then you match the line of the content of a shell variable called input. (Just look at the quotes and try to interpret the code yourself.) That variable is empty so awk matches the line against //, an empty regexp that always matches.

All you need to do is

$0 ~ input { print }

or

match( $0, input) { print }

Actually "{ print }" can be omitted becaus the default action for any matching matter is to print the record.

Gombai Sándor

Posted 2016-05-02T11:44:52.660

Reputation: 3 325

Thanks @Sándor for sorting out the error. I was pulling my hair out for this. :) – learner1 – 2016-05-02T12:22:01.043

Very welcome. I can imagine. Sometimes it quoting makes even simple cases look harder, other times it really makes them harder. – Gombai Sándor – 2016-05-02T12:27:47.293