AWK命令帮助

时间:2011-04-25 16:38:40

标签: unix awk

我有一个家庭作业,这就是问题。

使用awk创建一个命令,显示特定文件的每个字段。

在文件开头显示日期,输出头之间有一行和一个标题。

我已经阅读了这本书并且无法弄明白,这就是我所拥有的:

BEGIN {
{"date" | getline d }
{ printf "\t %s\n,d }
{ print "Heading\n" }
{ print "=====================\n }
}
{ code to display each field of file??? }

2 个答案:

答案 0 :(得分:3)

关于awk的一些提示:

awk程序的格式是

expression { action; ... }
expression { action; ... }
...

如果表达式的计算结果为true,则执行操作块。表达式的一些例子:

BEGIN       # true before any lines of input are read
END         # true after the last line of input has been read
/pattern/   # true if the current line matches the pattern
NR < 10     # true if the current line number is less than 10

等。如果希望在每一行上执行操作,则可以省略表达式。

所以,你的BEGIN块有太多大括号:

BEGIN {
    "date" | getline d 
    printf("\t %s\n\n",d)
    print "Heading" 
    print "====================="
}

你也可以写

BEGIN {
    system("date")
    print ""
    print "Heading" 
    print "====================="
}

或在awk之外执行date命令并将结果作为awk变量传递

awk -v d="$(date)" '
    BEGIN {
        printf("%s\n\n%s\n%s\n", 
            d,
            "heading",
            "======")
    }

print命令隐式地在输出中添加换行符,因此print "foo\n"; print "bar"将在“foo”之后打印一个空行。 printf命令要求您在格式字符串中添加换行符。

使用“打印每个字段的代码”无法帮助您。 Luuk表示print $0将打印所有字段。如果这不符合您的要求,您必须更加具体。

答案 1 :(得分:2)

{"date" | getline d }

为什么不简单地打印当前日期    {print strftime(“%y-%m-%d%H:%M”); }

和for:

{ code to display each field of file??? }

简单地做

{ print $0; }

如果您只想要第一个字段,那么:

{ print $1; }

如果您只想要第二个字段:

{print $2; }

如果您只想要最后一个字段:

{print $NF;}

因为NF是一条线上的场数......

相关问题