awk没有结束


8

我在名为的文件中包含以下代码awktest1.awk

#!/bin/awk -f
BEGIN{print "start"}
{print $2, "\t", $5}
END{print "end"} employee.txt

其中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

我将awk命令运行为:

awk -f awktest1.awk

但它只是打印start而不会结束。有人可以帮我解决我在这里做错的事情吗?


2
请注意,通过编写:print $2, "\t", $5与相对print $2 "\t" $5,您在编写第二个字段,然后是OFS(空格),TAB,OFS和第五个字段。
斯特凡Chazelas

Answers:


12

错误是在脚本中提供了要处理的文件名。您应该employee.txt从脚本中删除并按以下方式运行它

awk -f awktest1.awk employee.txt

甚至,如果脚本是可执行的,

./awktest1.awk employee.txt

脚本变成

#!/bin/awk -f
BEGIN{print "start"}
{print $2, "\t", $5}
END{print "end"}

实际上,它正在awk等待来自标准输入的输入,而不是从文件中读取。这就是为什么它永远不会结束...


12

为了补充@Stephen的答案,如果您想在awk脚本中对输入文件的名称进行硬编码,请编写:

#!/bin/awk -f
BEGIN{
  ARGC=2
  ARGV[1] = "employee.txt"
  OFS = FS = "\t"
  print "start"
}
{print $2, $5}
END{print "end"}

对于几个文件:

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

5

或者,如果您不想将文件名employee.txt作为命令行参数传递,则可以执行以下操作:

码:

#!/bin/awk -f
BEGIN{
    print "start"
    while((getline <"employee.txt") > 0){
        {print $2, "\t", $5}
    }
    print "end"
} 
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.