无法在AWK一个阶乘函数 [英] Unable to make a factorial function in AWK
问题描述
的code
#!/usr/bin/awk
# Sed and AWK by O'Reilly (p.179)
# Example of what should happen: factorial 5 gives
# factorial
# Enter number: 3
# The factorial of 3 is 6
BEGIN {
printf("Enter number: ")
}
$1 ~ /^[0-9]+$/ {
# assign value of $1 to number & fact
number = $1
if (number == 0)
fact = 1
else
fact = number
for (x = 1; x < number; x++)
fact *=x
printf("The factorial of %d is %g\n", number, fact)
exit
}
# if not a number, prompt again.
{ printf("\nInvalid entry. Enter a number: ")
}
我用
./factorial.awk
我得到
/usr/bin/awk: syntax error at source line 1
context is
>>> <<< ./factorial.awk
/usr/bin/awk: bailing out at source line 1
什么是错误讯息?
推荐答案
我觉得现在的问题是,你正在编写一个shell脚本,并通过它来awk的执行。下面是一个shell脚本,因此#! / bin / sh的
,所以它会被传递给shell(在这种情况下Bourne兼容)。
I think that the problem is that you are writing a shell script and passing it to awk for execution. The following is a shell script, hence the #! /bin/sh
, so it will be passed to the shell (Bourne-compatible in this case).
#! /bin/sh
awk 'BEGIN { printf("Hello world!\n"); exit }'
在她榜(#!)行告诉目前除preTER间preTER到脚本传递到执行它。你必须在脚本传递给 AWK
间preTER,所以你需要调用 AWK
明确。这假定 AWK
在路径的某个地方。
The she-bang (#!) line tells the current interpreter which interpreter to pass the script to for execution. You have to pass the script to the awk
interpreter so you need to call awk
explicitly. This assumes that awk
is in your path somewhere.
以下,然而,是 AWK
脚本。
#! /usr/bin/awk -f
BEGIN {
printf("Hello world!\n");
exit
}
在她邦调用 AWK
并通过脚本作为输入。你不需要在这种情况下,显式调用 AWK
键,因为它直接传递给 awk的<你不必引用整个脚本/ code>。
The she-bang invokes awk
and passes the script as input. You don't need to explicitly invoke awk
in this case and you don't have to quote the entire script since it is passed directly to awk
.
在她邦看作话说的采取什么样的跟随她爆炸,附加文件的名称,并执行的。 维基百科描述了使用pretty以及包括一些常见的方法来解决在<一个href=\"http://en.wikipedia.org/wiki/Shebang%5F%28Unix%29#Solving%5Fshebang%5Fproblems%5Fwith%5Fthe%5Fenv%5Fprogram\"相对=nofollow> 路径间preTER 的问题。
Think of the she-bang as saying take what follows the she-bang, append the name of the file, and execute it. Wikipedia describes the usage pretty well including some common ways to solve the path to the interpreter problem.
这篇关于无法在AWK一个阶乘函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!