Scripting

從字元串中刪除特定字元

  • April 25, 2019

我需要用逗號替換空格,然後從字元串中刪除某些額外的特定字元。

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

您可以通過一個 sed 呼叫來完成,例如

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

由於您的日期具有標準輸出和固定列數,您可以使用 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

引用自:https://unix.stackexchange.com/questions/513914