Rapahh
Rapahh

Reputation: 31

AWK command help

I have a homework assignment and this is the question.

Using awk create a command that will display each field of a specific file.

Show the date at the beginning of the file with a line between and a title at the head of the output.

I have read the book and can't quite figure it out, here is what I have:

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

Upvotes: 1

Views: 547

Answers (2)

glenn jackman
glenn jackman

Reputation: 246807

Some tips about awk:

The format of an awk program is

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

If the expression evaluates to true, then the action block is executed. Some examples of expressions:

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

etc. The expression can be omitted if you want the action to be performed on every line.

So, your BEGIN block has too many braces:

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

You could also write

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

or execute the date command outside of awk and pass the result in as an awk variable

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

The print command implicitly adds a newline to the output, so print "foo\n"; print "bar" will print a blank line after "foo". The printf command requires you to add newlines into your format string.

Can't help you more with "code to print each field". Luuk shows that print $0 will print all fields. If that doesn't meet your requirements, you'll have to be more specific.

Upvotes: 3

Luuk
Luuk

Reputation: 14929

{"date" | getline d }

why not simply print current date { print strftime("%y-%m-%d %H:%M"); }

and for:

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

simply do

{ print $0; }

if you only wanted the first field you should do:

{ print $1; }

if you only want the second field:

{print $2; }

if you want only the last field:

{print $NF;}

Because NF is the number of field on a line......

Upvotes: 2

Related Questions