我在名为 的文件中有以下代码awktest1.awk
:
#!/bin/awk -f
BEGIN{print "start"}
{print $2, "\t", $5}
END{print "end"} employee.txt
Run Code Online (Sandbox Code Playgroud)
其中employee.txt
包含以下数据:
100 Thomas Manager Sales $5,000
200 Jason Developer Technology $5,500
300 Sanjay Sysadmin Technology $7,000
400 Nisha Manager Marketing $9,500
500 Randy DBA Technology $6,000
Run Code Online (Sandbox Code Playgroud)
我运行awk
命令为:
awk -f awktest1.awk
Run Code Online (Sandbox Code Playgroud)
但它只是打印start
,并没有结束。谁能帮我解决我在这里做错了什么?
Ste*_*itt 12
错误是在脚本中给出要处理的文件名;您应该employee.txt
从脚本中删除并按如下方式运行它
awk -f awktest1.awk employee.txt
Run Code Online (Sandbox Code Playgroud)
甚至,如果脚本是可执行的,
./awktest1.awk employee.txt
Run Code Online (Sandbox Code Playgroud)
脚本变成
#!/bin/awk -f
BEGIN{print "start"}
{print $2, "\t", $5}
END{print "end"}
Run Code Online (Sandbox Code Playgroud)
实际上,awk
正在等待来自标准输入的输入而不是从文件中读取。这就是为什么它永远不会结束......
Sté*_*las 12
为了补充@Stephen 的回答,如果您想在awk
脚本中硬编码输入文件的名称,您可以编写:
#!/bin/awk -f
BEGIN{
ARGC=2
ARGV[1] = "employee.txt"
OFS = FS = "\t"
print "start"
}
{print $2, $5}
END{print "end"}
Run Code Online (Sandbox Code Playgroud)
对于多个文件:
#!/bin/awk -f
BEGIN{
ARGC=1
ARGV[ARGC++] = "employee1.txt"
ARGV[ARGC++] = "employee2.txt"
ARGV[ARGC++] = "employee3.txt"
# ...
# or ARGC=1+split("employee1.txt employee2.txt employee3.txt", ARGV)
OFS = FS = "\t"
print "start"
}
{print $2, $5}
END{print "end"}
Run Code Online (Sandbox Code Playgroud)
或者,如果您不想将文件名employee.txt
作为命令行参数传递,您可以执行以下操作:
#!/bin/awk -f
BEGIN{
print "start"
while((getline <"employee.txt") > 0){
{print $2, "\t", $5}
}
print "end"
}
Run Code Online (Sandbox Code Playgroud)