在Bash脚本中使用awk [英] using awk in Bash script
问题描述
我正在学习Bash脚本.我的 data.txt
包含:
I am learning Bash scripts.
my data.txt
contains:
A Orange
B Apple
我尝试过
echo "enter"
read fruit
awk -F'[: ]' '$2 == "Apple"' data.txt
a=`awk -F'[: ]' '\$2 == "$fruit"' data.txt` # returns null
echo "$a"
当我将变量'a'与它一起使用时,为什么我的awk命令不起作用?
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.
您想要使用时要做的事情:
'\$2 == "$fruit"' # DOES NOT WORK - nothing is escaped or expanded
是:
"\$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).
也就是说,最好将shell的世界和Awk脚本分开,以防止混淆,这意味着:
That said, it's better to keep the worlds of the shell and the Awk script separate, so as to prevent confusion, which means:
- 使用单引号字符串作为Awk脚本.
- 通过Awk的
-v
选项将任何shell变量值传递给脚本,以创建 Awk 变量.
- 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 `...`
.
这篇关于在Bash脚本中使用awk的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!