使用 awk 在 bash 中替换命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10492446/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 02:13:31  来源:igfitidea点击:

command substitution in bash with awk

linuxbash

提问by Ankur Agarwal

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

回答by Paused until further notice.

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. And by using single quotes, you won't have to do a bunch of unnecessary escaping.

将 shell 变量传递给 AWK 程序的正确方法是使用 AWK 的变量传递功能,而不是尝试嵌入 shell 变量。并且通过使用单引号,您将不必做一堆不必要的转义。

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

Also, you should use $()instead of backticks.

此外,您应该使用$()而不是反引号。

回答by Diego Torres Milano

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 >>>  (\ <<<  == "hello" ) print $2; }
awk: illegal statement at source line 1

furthermore, if you replace awkby echoyou'll see clearly why it fails

此外,如果你替换awkecho你会清楚地看到它失败的原因

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