Text-Processing

sed 命令交換字元

  • November 18, 2018

我的輸入文件佈局是:mm/dd/yyyy,hh:mm,other fields

我需要將其格式化為: yyyy-mm-dd hh:mm:00,other fields

樣本輸入:

01/02/1998,09:30,0.4571,0.4613,0.4529,0.4592,6042175
01/02/1998,09:45,0.4592,0.4613,0.4529,0.4571,9956023
01/02/1998,10:00,0.4571,0.4613,0.455,0.4613,8939555
01/02/1998,10:15,0.4613,0.4697,0.4571,0.4697,12823627
01/02/1998,10:30,0.4676,0.4969,0.4613,0.4906,28145145

樣本輸出:

1998-01-02 09:30:00,0.4571,0.4613,0.4529,0.4592,6042175
etc...

我嘗試使用:

sed -r 's/\(^[0-9][0-9])\(\/[0-9][0-9]\/)\(\/[0-9][0-9][0-9][0-9],)/\3\1\2/g
sed -e 's/\(..\)\/\(..\)\/\(....\),\(.....\),\(.*\)/\3-\1-\2 \4:00,\5/'

編輯以包括以下評論的輸入:

sed -e 's#\(..\).\(..\).\(....\),\(.....\),#\3-\1-\2 \4:00,#'

這對我有用:

sed -r 's/([0-9]{2})\/([0-9]{2})\/([0-9]{4}),([0-9:]{5})/\3-\1-\2 \4:00/g'

匹配 2 位數字 ( ([0-9]{2}))、斜線、2 位數字 ( ([0-9]{2}))、斜線、4 位數字 ( ([0-9]{4})),然後是數字和:( ([0-9:]{5}))。將其替換為您希望的順序:(\3-\1-\2 \4:00年-月-日時:分:00)。

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