首页 > 代码库 > sed正则经典案例(四)

sed正则经典案例(四)

sed正则经典案例(四)

###修改日期格式,已知文件内容如下:

原始数据:文件date.txt

21/May/2017:09:29:24 +0800
22/May/2017:09:30:26 +0800
23/May/2017:09:31:56 +0800
24/May/2017:09:34:12 +0800
25/May/2017:09:35:23 +0800
26/May/2017:09:23:34 +0800
27/May/2017:09:22:21 +0800
28/May/2017:09:45:22 +0800

期望结果1:

2017-05-21 09:29:24 +0800
2017-05-22 09:30:26 +0800
2017-05-23 09:31:56 +0800
2017-05-24 09:34:12 +0800
2017-05-25 09:35:23 +0800
2017-05-26 09:23:34 +0800
2017-05-27 09:22:21 +0800
2017-05-28 09:45:22 +0800

期望结果2:

Welcome to oldboy training!
2017-05-21 09:29:24 +0800
2017-05-22 09:30:26 +0800
2017-05-23 09:31:56 +0800
2017-05-24 09:34:12 +0800
2017-05-25 09:35:23 +0800
2017-05-26 09:23:34 +0800
2017-05-27 09:22:21 +0800
2017-05-28 09:45:22 +0800
I must be successful!

解答:
期望结果一方法汇总:

sed -nr ‘s#(..)/(...)/(....):(..):(..):(..) (.*)#\3-\2-\1 \4:\5:\6\7#;s#Apr#04#p‘ date.txt

awk ‘{sub(/May/,"05");split($0,array,"[/: ]") ;printf("%s-%s-%s %s:%s:%s%s\n",array[3],array[2],array[1],array[4],array[5],array[6],array[7])}‘ date.txt

期望结果二方法汇总:

sed -r ‘s#May#05#g;s#^([0-9]+)/([0-9]+)/([0-9]+):(.*) (.*$)#\3-\2-\1 \4 \5#g‘ date.txt|sed -e ‘1 i\Welcome to oldboy training!‘ -e ‘$ a\I must be successful!‘

sed -r ‘s#May#05#g;s#^([0-9]+)/([0-9]+)/([0-9]+):(.*) (.*$)#\3-\2-\1 \4 \5#g‘ date.txt|awk ‘BEGIN{print "Welcome to oldboy training!"}END{print "I must be successful!"}1‘ 

awk ‘{sub(/May/,"05");split($0,array,"[/: ]") ;printf("%s-%s-%s %s:%s:%s%s\n",array[3],array[2],array[1],array[4],array[5],array[6],array[7])}‘ date.txt|sed -e ‘1 i\Welcome to oldboy training!‘ -e ‘$ a\I must be successful!‘

awk ‘{sub(/May/,"05");split($0,array,"[/: ]") ;printf("%s-%s-%s %s:%s:%s%s\n",array[3],array[2],array[1],array[4],array[5],array[6],array[7])}‘ date.txt|awk ‘BEGIN{print "Welcome to oldboy training!"}END{print "I must be successful!"}1‘


sed正则经典案例(四)