1

I want to replace in this string Wed Apr 10 06:44:10 UTC 2019 all whitespaces with comma and along with that trim off UTC part.

What I have tried :

var1="Wed Apr 10 06:44:10 UTC 2019"
echo ${var// /,}

This gives all spaces removed but how to trim off UTC part, I want to achieve this in one line command.

Alex
  • 172
  • 1
  • 1
  • 8

3 Answers3

3

IMHO Typically date/time manipulation works better when you treat a time string as time and not a text string.

Use the formatting options of the date command to get the timestamp to display in your desired formatting and do something along the lines of:

var1="Wed Apr 10 06:44:10 UTC 2019"
date --date="$var1" +%Y,%m,%d  

and you can for instance also ensure that the day component of "Wed Apr 9" gets padded to 09 etc.

HBruijn
  • 72,524
  • 21
  • 127
  • 192
  • I need to save this in a variable as well :-) will this work ? date --date=$("$var1" +%y,%m,%d) – Alex Apr 10 '19 at 08:59
  • You can indeed do `newtime=$(date --date="$var1" +%Y,%m,%d)` or similar to save the new format for further use – HBruijn Apr 10 '19 at 09:00
1

If you just want to manipulate the existing string and remove "UTC 2019" or "UTC":

# remove "UTC 2019"
$ echo ${var1/UTC*}|tr ' ' ,
Wed,Apr,10,06:44:10

# store the result in a variable
$ var2=$(echo ${var1/UTC*}|tr ' ' ,)

# remove "UTC"
$ echo ${var1/UTC}|tr ' ' ,
Wed,Apr,10,06:44:10,2019
Freddy
  • 1,999
  • 5
  • 12
0

"Danger, Will Robinson!"

Whilst it's not immediately obvious, watch out for this one:

If the time zone on the machine changes then, suddenly, the date isn't in UTC any more, so any code you may write to remove the "UTC" moniker won't do anything and you'll be left with an extra value in your result that will foul up your downstream logic.

Wed Apr 10 06:44:10 UTC 2019  ->  Wed,Apr,10,06:44:10,2019       OK

Wed Apr 10 11:22:18 BST 2019  ->  Wed,Apr,10,11:22:18,BST,2019   Oops!
                    ^^^                               ^^^

As others have said, format your date in more predictable ways.

Phill W.
  • 1,336
  • 7
  • 7