4

In an awk, script I am using a command

system(date)

to print the current date in a file, but after this command is executed, the next line is also added implicitly. Is there any way in awk to print the current date without the new line being added so that whatever I print next comes in the same line?

3

The date command adds a newline at the end of its output. You can read the output into awk and make it print without appending a newline.

"date" | getline date; printf "%s", date

Unless your script is long-running, you could alternatively obtain the date when you start your script.

awk -v date="$(date)" '
    … printf "%s", date …
'
| improve this answer | |
  • @Gilles-every thing is working fine but it gives an error /bin/sh: 1 :not found .I am using it like this:- – nishan May 6 '11 at 19:36
  • @Gilles-every thing is working fine but it gives an error /bin/sh: 1 :not found .I am using it like this:- system("date"| getline date) printf("%s",date) – nishan May 6 '11 at 19:44
  • 1
    @nishan: The pipe executes its left-hand side as a command. So you're executing the result of system(…) as a shell command. The right syntax is in my answer. – Gilles 'SO- stop being evil' May 6 '11 at 20:00
1

The GNU awk and @ThomasDickey's mawk implementations of awk has some extensions relating to time and date functionality. With these, you could use

strftime("%+", systime())

to get a string representation in the same format as the date utility would produce.

Or, for a slightly different format, but more portable (works on non-BSD systems),

strftime("%c", systime())

Testing:

$ date
Mon Jan 28 11:22:22 CET 2019
$ gawk 'BEGIN { print strftime("%+", systime()) }'
Mon Jan 28 11:22:27 CET 2019
$ mawk 'BEGIN { print strftime("%+", systime()) }'
Mon Jan 28 11:22:33 CET 2019

If the %+ format is not supported on your system (it's not in glibc2), then %c would probably generate a close approximation to this. The exact format will depend on the implementation of strftime() in the C library, and on the current datetime-related locale settings. In the C/POSIX locale, you would get the same output as above, but with no time-zone abbreviation.

BSD awk implementation may not have these functions by default.

See also:

  • The manuals for awk and strftime (for time/date-stamp formatting) on your system.
| improve this answer | |
  • That would be @ThomasDickey's mawk (since 20121129). Note that the one that comes with Debian and derivatives doesn't have those extensions. %+ support is also probably system dependant. – Stéphane Chazelas Jan 28 '19 at 11:29
  • @StéphaneChazelas Some of that has now been addressed. Thanks. – Kusalananda Jan 28 '19 at 12:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.