echo '((3+(2^3)) * 34^2 / 9)-75.89' | awk "BEGIN{ print $(cat) }"
Run Code Online (Sandbox Code Playgroud)
上述语法适用于计算结果“1337”。
echo '((3+(2^3)) * 34^2 / 9)-75.89' | awk "BEGIN{ print $* }"
Run Code Online (Sandbox Code Playgroud)
但是上面的语法不起作用,尽管没有错误。
请各位指教。
ter*_*don 13
该$(command)
语法将返回的输出command
。在这里,您使用的是非常简单的cat
程序,它的唯一工作是将所有内容从标准输入 (stdin) 复制到标准输出 (stdout)。由于您awk
在双引号内运行脚本,$(cat)
shell在awk
脚本运行之前对其进行了扩展,因此它将echo
输出读入其标准输入并适当地将其复制到标准输出。然后将其传递给awk
脚本。您可以通过以下方式看到这一点set -x
:
$ set -x
$ echo '((3+(2^3)) * 34^2 / 9)-75.89' | awk "BEGIN{ print $(cat) }"
+ echo '((3+(2^3)) * 34^2 / 9)-75.89'
++ cat
+ awk 'BEGIN{ print ((3+(2^3)) * 34^2 / 9)-75.89 }'
1337
Run Code Online (Sandbox Code Playgroud)
所以,awk
实际上正在运行BEGIN{ print ((3+(2^3)) * 34^2 / 9)-75.89 }'
,返回 1337。
现在,$*
是一个特殊的 shell 变量,它扩展为提供给 shell 脚本的所有位置参数(请参阅 参考资料man bash
):
* Expands to the positional parameters, starting from one. When the expan?
sion is not within double quotes, each positional parameter expands to a
separate word. In contexts where it is performed, those words are sub?
ject to further word splitting and pathname expansion. When the expan?
sion occurs within double quotes, it expands to a single word with the
value of each parameter separated by the first character of the IFS spe?
cial variable. That is, "$*" is equivalent to "$1c$2c...", where c is
the first character of the value of the IFS variable. If IFS is unset,
the parameters are separated by spaces. If IFS is null, the parameters
are joined without intervening separators.
Run Code Online (Sandbox Code Playgroud)
然而,这个变量在这里是空的。因此,awk
脚本变为:
$ echo '((3+(2^3)) * 34^2 / 9)-75.89' | awk "BEGIN{ print $* }"
+ awk 'BEGIN{ print }'
+ echo '((3+(2^3)) * 34^2 / 9)-75.89'
Run Code Online (Sandbox Code Playgroud)
该$*
扩展为空字符串,并且awk
被告知要打印一个空字符串,这就是为什么你没有输出。
您可能只想使用bc
:
$ echo '((3+(2^3)) * 34^2 / 9)-75.89' | bc
1336.11
Run Code Online (Sandbox Code Playgroud)