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.

3 Answers 3

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.

2
  • I need to save this in a variable as well :-) will this work ? date --date=$("$var1" +%y,%m,%d) Commented Apr 10, 2019 at 8:59
  • You can indeed do newtime=$(date --date="$var1" +%Y,%m,%d) or similar to save the new format for further use Commented Apr 10, 2019 at 9: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 
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.

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.