1

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?

3 Answers 3

4

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.

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

Comments

3

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?

Comments

2

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.