简体   繁体   English

使用awk在bash中命令替换

[英]command substitution in bash with awk

Why does this work: 为什么这样做:

This 这个

var=hello
myvar=`echo hello hi | awk "{ if (\\\$1 == \"$var\" ) print \\\$2; }"`
echo $myvar

gives

hi

But this does not? 但这不是吗?

This 这个

var=hello
echo hello hi | awk "{ if (\\\$1 == \"$var\" ) print \\\$2; }"

gives

awk: cmd. line:1: Unexpected token

I am using 我在用

GNU bash, version 4.1.5(1)-release (i486-pc-linux-gnu) GNU bash,版本4.1.5(1)-release(i486-pc-linux-gnu)

on

Linux 2.6.32-34-generic-pae #77-Ubuntu SMP Tue Sep 13 21:16:18 UTC 2011 i686 GNU/Linux Linux 2.6.32-34-generic-pae#77-Ubuntu SMP Tue Sep 13 21:16:18 UTC 2011 i686 GNU / Linux

The correct way to pass shell variables into an AWK program is to use AWK's variable passing feature instead of trying to embed the shell variable. 将shell变量传递给AWK程序的正确方法是使用AWK的变量传递功能,而不是尝试嵌入shell变量。 And by using single quotes, you won't have to do a bunch of unnecessary escaping. 通过使用单引号,您不必进行一堆不必要的转义。

echo "hello hi" | awk -v var="$var" '{ if ($1 == var ) print $2; }'

Also, you should use $() instead of backticks. 此外,您应该使用$()而不是反引号。

If your awk is like mine, it will tell you where it fails: 如果你的awk和我的一样,它会告诉你失败的地方:

var=hello
echo hello hi | awk "{ if (\\\$1 == \"$var\" ) print \\\$2; }"

awk: syntax error at source line 1
 context is
    { if >>>  (\ <<< $1 == "hello" ) print \$2; }
awk: illegal statement at source line 1

furthermore, if you replace awk by echo you'll see clearly why it fails 此外,如果你用echo替换awk ,你会清楚地看到它失败的原因

echo hello hi | echo "{ if (\\\$1 == \"$var\" ) print \\\$2; }"
{ if (\$1 == "hello" ) print \$2; }

there are extra '\\' (backslashes) in the resulting command. 结果命令中有额外的'\\'(反斜杠)。 This is because you removed the backquotes. 这是因为你删除了反引号。 So the solutions is to remove a pair of \\'s 因此,解决方案是删除一对

echo hello hi | awk "{ if (\$1 == \"$var\" ) print \$2; }"
hi

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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