简体   繁体   中英

using awk in Bash script

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?

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 `...` .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM