从字符串中删除特定字符

从字符串中删除特定字符

我需要用逗号替换空格,然后从字符串中删除某些额外的特定字符。

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

但我又想删除 UTC 部分和前面的逗号,我该如何实现呢?

期望的输出应该是

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

答案1

您可以通过一次 sed 调用来完成此操作,例如

$ echo "Mon Apr 22 05:06:00 UTC 2019" | sed 's/ \(UTC \)\?/,/g'
Mon,Apr,22,05:06:00,2019

答案2

由于您的日期具有标准输出和固定的列数,因此您可以使用 awk 打印所需的数据

[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

答案3

你可以简单地说:

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

答案4

我已经使用 awk 和 sed 通过以下方法完成了。

命令:

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

输出:

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

相关内容