15

So I need to convert a date to a different format. With a bash pipeline, I'm taking the date from the last console login, and pulling the relevant bits out with awk, like so:

last $USER | grep console | head -1 | awk '{print $4, $5}'

Which outputs: Aug 08 ($4=Aug $5=08, in this case.)

Now, I want to take 'Aug 08' and put it into a date command to change the format to a numerical date.

Which would look something like this:

date -j -f %b\ %d Aug\ 08 +%m-%d

Outputs: 08-08

The question I have is, how do I add that to my pipeline and use the awk variables $4 and $5 where 'Aug 08' is in that date command?

3
  • You're actually asking how to use the output from awk, not the variables, in the other command. Commented Aug 10, 2010 at 18:55
  • What version of date (and the OS, etc.)? GNU date doesn't have -j and it uses -f for reading from a file. Your command would be date -d Aug\ 08 +%m-%d Commented Aug 10, 2010 at 20:43
  • Not sure of the exact version number -- doesn't have any sort of --version output. It's a BSD build on Mac OSX, so I put together the date options based on the man page on OS X 10.6. Only intending to run the script on mac clients, but thanks for the info; it'll be useful should I need to do something similar on Linux. Commented Aug 11, 2010 at 0:05

4 Answers 4

19

You just need to use command substitution:

date ... $(last $USER | ... | awk '...') ...

Bash will evaluate the command/pipeline inside the $(...) and place the result there.

Sign up to request clarification or add additional context in comments.

Comments

6

Get awk to call date:

... | awk '{system("date -j -f %b\ %d \"" $4 $5 "\" +%b-%d")}'

Or use process substitution to retrieve the output from awk:

date -j -f %b\ %d "$(... | awk '{print $4, $5}')" +%b-%d

Comments

0

Using back ticks should work to get the output of your long pipeline into date.

date -j -f %b\ %d \`last $USER | grep console | head -1 | awk '{print $4, $5}'\` +%b-%d

1 Comment

It may not matter in this case, but in general it's far better to use $(...) than backticks. It can be nested.
-1

I'm guessing you already tried this?

last $USER | grep console | head -1 | awk | date -j -f %b\ %d $4 $5 +%b-%d

1 Comment

This does not work. awk requires parameters, and it's output is not routed to date's parameters

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.