无法在 AWK 中创建阶乘函数

发布于 2024-07-17 06:24:33 字数 933 浏览 6 评论 0原文

代码

 #!/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

错误消息是什么意思?

The 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: ")
 }

I run the command unsuccessfully by

./factorial.awk

I get

/usr/bin/awk: syntax error at source line 1
 context is
         >>>  <<< ./factorial.awk
/usr/bin/awk: bailing out at source line 1

What does the error message mean?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

Spring初心 2024-07-24 06:24:33

我认为问题在于您正在编写一个 shell 脚本并将其传递给 awk 执行。 以下是 shell 脚本,因此是 #! /bin/sh,因此它将被传递到 shell(在本例中是 Bourne 兼容的)。

#! /bin/sh
awk 'BEGIN { printf("Hello world!\n"); exit }'

she-bang (#!) 行告诉当前解释器将脚本传递给哪个解释器来执行。 您必须将脚本传递给 awk 解释器,因此您需要显式调用 awk。 这假设 awk 在您的路径中的某个位置。

然而,以下是一个 awk 脚本。

#! /usr/bin/awk -f
BEGIN {
    printf("Hello world!\n");
    exit
}

she-bang 调用 awk 并将脚本作为输入传递。 在这种情况下,您不需要显式调用 awk,也不需要引用整个脚本,因为它直接传递给 awk

将 she-bang 想象为获取 she-bang 之后的内容,附加文件名,然后执行它维基百科很好地描述了用法,包括一些解决解释器路径问题。

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 }'

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.

The following, however, is an awk script.

#! /usr/bin/awk -f
BEGIN {
    printf("Hello world!\n");
    exit
}

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.

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.

清风无影 2024-07-24 06:24:33

可能是一个愚蠢的答案,但在我的终端中,我必须输入:

./factorial.awk

其中文件是factorial.awk。

您可以编辑路径环境变量以包含 . 但我认为 ./ 应该可以正常工作。 并添加 . 在某些情况下,添加到 $PATH 可能会非常危险,因为您会运行您不期望的代码。

那样有用吗??

编辑:

./factorial.awk
-bash: ./factorial.awk: /usr/bin/gawk: badterpreter: No such file or directory

这表示它运行了该文件,但找不到程序 gawk。
请输入“which gawk”,然后输入“which awk”。

你的第一行应该是:

#!/usr/bin/awk

另外,只是为了逗我,输入:

sudo apt-get install gawk

这将确保你的系统上确实有gawk。

编辑2:
我看了你的代码,这就是我现在所拥有的。 我删除了两个引号和破折号。

#!/usr/bin/gawk                                                                                                                                        

# I think we do not need these (p.179) so I comment them out, since I do not know where else to put them.
# The same bug occurs also with them.
#fact = number
#for (x = number -1 ; x > 1; x--)
#    fact *= x

awk # factorial: returns factorial of user-supplied number
    BEGIN {
    printf("Enter number: ")
    }

   $1 ~ /^[0-9]+$/ {
   # assign value of $1 to number & fact
   number = $1 
   if (number == 0) 
       fact = 1
   else
       fact = number
   #loop to multiply fact*x until x = 1
   for (x = number - 1; x > 1; x--)
       fact *= x
   printf("The factorial of %d is %g\n", number, fact)
   #exit -- saves user from typing ^-d
   exit
}

# if not a number, prompt again.
{ printf("\nInvalid entry. Enter a number: ")
}

Possibly a dumb answer but in my terminal I would have to type in:

./factorial.awk

where the file is factorial.awk.

You could edit your path environment variable to include . but ./ should work just fine I think. And adding . to $PATH could prove to be very dangerous in some situations where you would run code that you did not expect to.

Does that work??

EDIT:

./factorial.awk
-bash: ./factorial.awk: /usr/bin/gawk: bad interpreter: No such file or directory

That says that it ran the file but could not find the program gawk.
Please type in 'which gawk' and then 'which awk'.

Is your first line supposed to be:

#!/usr/bin/awk

Also, just to amuse me, type in:

sudo apt-get install gawk

That will make sure you actually have gawk on your system.

EDIT2:
I took a look at your code and this is what I have now. I removed two quotes and a dash.

#!/usr/bin/gawk                                                                                                                                        

# I think we do not need these (p.179) so I comment them out, since I do not know where else to put them.
# The same bug occurs also with them.
#fact = number
#for (x = number -1 ; x > 1; x--)
#    fact *= x

awk # factorial: returns factorial of user-supplied number
    BEGIN {
    printf("Enter number: ")
    }

   $1 ~ /^[0-9]+$/ {
   # assign value of $1 to number & fact
   number = $1 
   if (number == 0) 
       fact = 1
   else
       fact = number
   #loop to multiply fact*x until x = 1
   for (x = number - 1; x > 1; x--)
       fact *= x
   printf("The factorial of %d is %g\n", number, fact)
   #exit -- saves user from typing ^-d
   exit
}

# if not a number, prompt again.
{ printf("\nInvalid entry. Enter a number: ")
}
南巷近海 2024-07-24 06:24:33

也许事情并没有那么复杂。

#!/usr/bin/awk ---------> #!/usr/bin/awk -f

may be it wasn't that complicated.

#!/usr/bin/awk ---------> #!/usr/bin/awk -f

苍暮颜 2024-07-24 06:24:33

检查是否有文件/usr/bin/gawk; 如果没有,请使用 awk 的路径或 gawk 的正确位置。

另外,你使脚本可执行吗?

另外,你的 PATH 中有当前目录吗?

Check whether there is a file /usr/bin/gawk; if not, use either the path of awk or the correct location for gawk.

Also, did you make the script executable?

And also, do you have the current directory in your PATH?

西瑶 2024-07-24 06:24:33

我通过运行让脚本在 Ubuntu 和 OS X 中工作

awk -f factorial.awk

似乎你不能按如下方式运行脚本,尽管书上是这么说的

./factorial.awk 

I got the script to work in Ubuntu and OS X by running

awk -f factorial.awk

It seems that you cannot run the script as follows although the book says so

./factorial.awk 
南巷近海 2024-07-24 06:24:33

这个问题是 Google 上搜索短语“awk阶乘”的热门问题,因此这里有一个在 awk 中打印阶乘的简单方法:

$ awk 'BEGIN{x=1;for(i=2;i<=6;i++)x*=i;print x}'
720

作为 shell 函数(nawk 需要 -v 之后的空格macOS 附带,但不是 gawk 提供的):

$ fac(){ awk -v "n=$1" 'BEGIN{x=1;for(i=2;i<=n;i++)x*=i;print x}';}
$ fac 6
720

作为计算 k 组合的 awk 函数:

$ awk 'function f(x){r=1;for(i=2;i<=x;i++)r*=i;return r}BEGIN{n=5;k=3;print f(n)/(f(k)*f(n-k))}'
10

This question was the top hit on Google for the search phrase "awk factorial", so here's a simple way to print a factorial in awk:

$ awk 'BEGIN{x=1;for(i=2;i<=6;i++)x*=i;print x}'
720

As a shell function (the space after -v is required by nawk which comes with macOS but not by gawk):

$ fac(){ awk -v "n=$1" 'BEGIN{x=1;for(i=2;i<=n;i++)x*=i;print x}';}
$ fac 6
720

As an awk function for calculating k-combinations:

$ awk 'function f(x){r=1;for(i=2;i<=x;i++)r*=i;return r}BEGIN{n=5;k=3;print f(n)/(f(k)*f(n-k))}'
10
囍笑 2024-07-24 06:24:33

这是一个递归版本:

#!/usr/bin/awk -f
function f(x) {
    if (x <= 1) return 1
    return (f(x-1) *x)} 

BEGIN {
    printf("Enter number: ")
}

$1 ~ /^[0-9]+$/ {
    printf("The factorial of %d is %d\n", $1, f($1))
    exit
}

{ printf("\nInvalid entry. Enter a number: ")
}

Here's a recursive version:

#!/usr/bin/awk -f
function f(x) {
    if (x <= 1) return 1
    return (f(x-1) *x)} 

BEGIN {
    printf("Enter number: ")
}

$1 ~ /^[0-9]+$/ {
    printf("The factorial of %d is %d\n", $1, f($1))
    exit
}

{ printf("\nInvalid entry. Enter a number: ")
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文