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 ?

1 Answer 1

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.

2
  • Thanks @Sándor for sorting out the error. I was pulling my hair out for this. :)
    – learner1
    May 2, 2016 at 12:22
  • Very welcome. I can imagine. Sometimes it quoting makes even simple cases look harder, other times it really makes them harder.
    – user556625
    May 2, 2016 at 12:27

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .