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?

Bart
  • 2,221

5 Answers5

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
Jim L.
  • 7,997
  • 1
  • 13
  • 27
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
$
steve
  • 21,892
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
FloHe
  • 860
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