awk 脚本头:#!/bin/bash 或 #!/bin/awk -f?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4670286/
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
awk script header: #!/bin/bash or #!/bin/awk -f?
提问by anvd
In an awk file, e.g example.awk, should the header be #!/bin/bashor #!/bin/awk -f?
在 awk 文件中,例如 example.awk,标题应该是#!/bin/bash还是#!/bin/awk -f?
The reason for my question is that if I try this command in the console I receive the correct file.txt with "line of text":
我的问题的原因是,如果我在控制台中尝试此命令,我会收到带有“文本行”的正确 file.txt:
awk 'BEGIN {print "line of text"}' >> file.txt
but if i try execute the following file with ./example.awk:
但如果我尝试使用 ./example.awk 执行以下文件:
#! /bin/awk -f
awk 'BEGIN {print "line of text"}' >> file.txt
it returns an error:
它返回一个错误:
$ ./awk-usage.awk
awk: ./awk-usage.awk:3: awk 'BEGIN {print "line of text"}' >> file.txt
awk: ./awk-usage.awk:3: ^ invalid char ''' in expression
If I change the header to #!/bin/bashor #!/bin/shit works.
如果我将标题更改为#!/bin/bash或 #!/bin/sh它有效。
What is my error? What is the reason of that?
我的错误是什么?那是什么原因呢?
回答by moinudin
Since you explicitly run the awkcommand, you should use #!/bin/bash. You can use #!/bin/awkif you remove the awkcommand and include only the awkprogram (e.g. BEGIN {print "line of text"}), but then you need to append to fileusing awk syntax (print ... >> file).
由于您显式运行该awk命令,因此您应该使用#!/bin/bash. 您可以使用#!/bin/awk,如果你删除awk命令,并只包括awk程序(例如BEGIN {print "line of text"}),但你必须要追加到file用awk语法(print ... >> file)。
awk -ftakes a file containing the awk script, so that is completely wrong here.
awk -f需要一个包含 awk 脚本的文件,所以这里是完全错误的。
回答by Residuum
Your script is a shell script that happens to contains an awk command.
您的脚本是一个 shell 脚本,恰好包含一个 awk 命令。
#! /bin/shtells your shell to execute the file as a shell command with /bin/sh- and it is a shell command. If you replace that with #! /bin/awk -fthen the file is executed with awk, basically the same as executing
#! /bin/sh告诉您的 shell 将文件作为带有/bin/sh-的 shell 命令执行,它是一个 shell 命令。如果将其替换为 ,#! /bin/awk -f则文件将使用 awk 执行,与执行基本相同
/bin/awk -f awk 'BEGIN {print "line of text"}' >> file.txt

