Reputation: 493
I got this simple bash script:
#! /bin/bash
DATE=$(date +"%d%m%Y%H%M")
DATETIME=$DATE | awk '{print substr($1,1,2)"."substr($1,3,2)"."substr($1,5,4)", "substr($1,9,2)":"substr($1,11,2)}'
echo $DATETIME
The output of variable DATE is e.g.
250520141600
and the output of variable DATETIME should be:
25.05.2014, 16:00
but I got nothing.
What's wrong?
Upvotes: 1
Views: 127
Reputation: 74596
There's no need to use awk
to format the output. Just do this:
$ DATETIME=$(date +"%d.%m.%Y, %H:%M")
$ echo "$DATETIME"
25.05.2014, 15:21
That said, you might want to store one date and display it in a number of different ways. To do that, I would recommend using date
, rather than awk
:
$ DATE=$(date)
$ echo "$DATE"
Sun May 25 15:39:09 BST 2014
$ date -d "$DATE" +"%d%m%Y%H%M"
250520141539
$ date -d "$DATE" +"%d.%m.%Y, %H:%M"
25.05.2014, 15:39
as well as displaying the current date/time, date
can also be passed a string containing a date and reformat it for you.
Upvotes: 4
Reputation: 78650
It is not working because you did not echo
the content of DATE
before piping it to awk
.
>> DATE=$(date +"%d%m%Y%H%M")
>> DATETIME=$(echo $DATE | awk '{print substr($1,1,2)"."substr($1,3,2)"."substr($1,5,4)", "substr($1,9,2)":"substr($1,11,2)}')
>> echo $DATETIME
25.05.2014, 16:07
Upvotes: 2
Reputation: 7153
You need to invoke a command and put the output in the variable. Since the output has spaces, it should be quoted.
DATETIME="$(echo $DATE | awk ...)"
Also, why not just adjust the date output to be the format you want?
Upvotes: 3