我有以下 csv
9999999,012021,I,0099999999,000000000099999999+,000000000000000000-,000000000000000000-
9999999,012021,I,0099999999,000000000099999999+,000000000000000000-,000000000000000000-
9999999,012021,I,0099999999,000000000099999999+,000000000000000000-,000000000000000000-
9999999,012021,I,0099999999,000000000099999999+,000000000000000000-,000000000000000000-
我想格式化第二列,始终将第 01 天添加为日期
9999999,2021-01-01,I,0099999999,000000000099999999+,000000000000000000-,000000000000000000-
9999999,2021-01-01,I,0099999999,000000000099999999+,000000000000000000-,000000000000000000-
答案1
像这样的东西awk
可以完成这项工作:
awk -F, 'BEGIN {OFS=","} {a=substr($2,1,2);b=substr($2,3,4);$2=b"-"a"-01";print $0}' input_file
请注意,这几乎适用于任何awk
.对于 Solaris 使用/usr/xpg4/bin/awk
或/usr/xpg6/bin/awk
(请参阅@EdMorton 评论)
PS 我假设 in012021
01
是月份,2021
是年份
答案2
使用sed
$ sed 's/\([^,]*,\)\([0-9]\{2\}\)\([^,]*\)\(.*\)/\1\3-\2-01\4/' input_file
9999999,2021-01-01,I,0099999999,000000000099999999+,000000000000000000-,000000000000000000-
9999999,2021-01-01,I,0099999999,000000000099999999+,000000000000000000-,000000000000000000-
9999999,2021-01-01,I,0099999999,000000000099999999+,000000000000000000-,000000000000000000-
9999999,2021-01-01,I,0099999999,000000000099999999+,000000000000000000-,000000000000000000-