0

I need to replace spaces with comma and then remove certain extra specific chars from a string.

echo "$d"
>>Mon Apr 22 05:06:00 UTC 2019
jent=$(echo $jt1 | sed 's/[[:space:]]/,/g')
echo "$jent"
>>Mon,Apr,22,05:06:00,UTC,2019 #this does the first job of replacing the space with comma

But again I want to remove the UTC part and the comma before it, how can I achieve it?

desired output should be

Mon,Apr,22,05:06:00,2019

migrated from serverfault.com Apr 22 at 23:34

This question came from our site for system and network administrators.

2

You can do it with one sed call, e.g.

$ echo "Mon Apr 22 05:06:00 UTC 2019" | sed 's/ \(UTC \)\?/,/g'
Mon,Apr,22,05:06:00,2019
  • Note that \? is a GNU extension, you can replace it with \{0,1\} for better portability. – Stéphane Chazelas Apr 25 at 11:36
1

Since your date has standard output and fix number of columns you can use awk to print the wanted data

[user@server1 ~]$ echo "Mon Apr 22 05:06:00 UTC 2019" | awk '{print $1","$2","$3","$4","$6}'
Mon,Apr,22,05:06:00,2019
0

You can simply say:

~]$ export jent="$(echo $jent | sed 's/,UTC//g')"
~]$ echo $jent
Mon,Apr,22,05:06:00,2019
0

You can do it with translate command:

jent=$(echo "$d" | tr -ds  UTC "  " | tr " " ,)
# the first double quotes contains two spaces 
echo "$jent"
Mon,Apr,22,05:06:00,2019
  • That's not how tr works. That would change Tue to ue for instance. – Stéphane Chazelas Apr 25 at 11:41
0

I have done by below method using awk and sed.

command:

echo "Mon Apr 22 05:06:00 UTC 2019"|awk '{$(NF-1)="";print $0}'| sed -r "s/\s+/ /g"| sed "s/ /,/g"

output:

Mon,Apr,22,05:06:00,2019
0

You can always do one substitution after the other in one sed invocation:

$ echo "Mon Apr 22 05:06:00 UTC 2019" | sed 's/ \{1,\}/,/g; s/,UTC,/,/'
Mon,Apr,22,05:06:00,2019

The \{1,\} is to cover the case where the day is padded to width 2 in the input as in:

$ echo "Mon Apr  2 05:06:00 UTC 2019" | sed 's/ \{1,\}/,/g; s/,UTC,/,/'
Mon,Apr,2,05:06:00,2019

Note that if it's to process the output of date, you could tell date to output in the format you want to start with:

$ LC_ALL=C date -u +%a,%b,%-d,%T,%Y
Thu,Apr,25,11:47:25,2019

%-d (to avoid the padding) is not standard but pretty common.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.