1

I have a bash script that takes user-inputed dates in this format: dd.mm.yyyy and saves it as a variable $date

Now I need to modify this variable to be in this format: yyyymmdd for further use.

So no more dots and back to front for the values between the dots.

Is there an easy way to do this kind of thing with sed for example?

1

5 Answers 5

2

Here's a pure bash solution:

$ # input is dd.mm.yyyy
$ input_date="dd.mm.yyyy"
$ # output will be yyyymmdd
$ output_date=${input_date:6:4}${input_date:3:2}${input_date:0:2}
$ echo "$output_date"
yyyymmdd
1
  • This worked perfect for my needs thank you so much :D Commented Aug 6, 2019 at 8:31
1

Here's my simplistic sed approach. Not particularly clever but works :-)

$ IN=12.34.5678
$ OUT=$(echo $IN | sed 's/\(..\).\(..\).\(....\)/\3\2\1/')
$ echo $OUT
56783412
$

awk approach

$ OUT=$(echo $IN | awk -F. '{print $3$2$1}')
$ echo $OUT
56783412
$

tr/tac/paste hybrid

$ OUT=$(echo $IN | tr '.' '\n' | tac | paste -s -d "")
$ echo $OUT
56783412
$
1
echo "26.11.2016" | awk -F"." '{print $3$2$1}'

Output: 20161126

0

Or awk:

$ date=03.06.1990
$ awk 'BEGIN { FS="."; OFS="" } { tmp=$1; $1=$3; $3=tmp }1' <<< "$date"
19900603
1
  • Or just awk -F. '{print $3$2$1}' <<< $date Commented Aug 5, 2019 at 21:54
0

The date command can output in ISO8601 format, with a modifier:

robert@pip2:/tmp$ date
Mon Aug  5 16:09:35 PDT 2019

robert@pip2:/tmp$ date --iso-8601
2019-08-05

...then just remove the hyphens in between. Using sed:

robert@pip2:/tmp$ date --iso-8601 | sed s/-//g
20190805

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.