1

I am learning Bash scripts. my data.txt contains:

A Orange
B Apple

I have tried

echo "enter"
read fruit
awk -F'[: ]' '$2 == "Apple"' data.txt
a=`awk -F'[: ]' '\$2 == "$fruit"' data.txt` # returns null
echo "$a"

Why isn't my awk command is not working when I am using my variable 'a' with it?

0

1 Answer 1

2

The crux of the problem is that you're trying to use a single-quoted string as if it were a double-quoted one.

What you meant to do when you used:

'\$2 == "$fruit"' # DOES NOT WORK - nothing is escaped or expanded

was:

"\$2 == \"$fruit\""  # keep literal $2, expand $fruit

Anything inside a single-quoted shell string is taken literally, so variable references aren't expanded, and nothing needs escaping - nor indeed can be escaped (the \ would become a literal part of the string too).

That said, it's better to keep the worlds of the shell and the Awk script separate, so as to prevent confusion, which means:

  • Use a single-quoted string as the Awk script.
  • Pass any shell-variable values to the script via Awk's -v option to create Awk variables.

If we put it all together:

a=$(awk -F'[: ]' -v fruit="$fruit" '$2 == fruit' data.txt)

Note that I've used modern command-substitution syntax $(...), which is preferable to legacy syntax `...`.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.