Chinaunix

标题: 将txt文件装换成csv文件 [打印本页]

作者: fzhcl    时间: 2014-01-05 12:37
标题: 将txt文件装换成csv文件
在Llinux 下, 本人需将以下的文本文件 a.txt 转换成csv文件,第一,第二列,第三列mapping csv的第一第二第三列,第三列没有固定的格式。

tdecom34        /config/TDAMINFOS.conf        /td/logs/httpd/tda.soc.tdgroup.com_error_log.*
tdecom34        /config/TDAMINFOS.conf        /td/logs/httpd/ihs_BBPGen34_httpd_plugin.log
tdecom34        /config/TDAMINFOS.fmt        (SSL0221E: SSL Handshake Failed)
tdecom34        /config/TDAMINFOS.fmt        (Marking)(?:.*)(down)
tdecom34        /config/OVN.fmt                        (Failed to execute the transaction to)(.*)(ecawap)(.*)(_node_OvationWS)
tdecom34        /config/BSL.fmt                        (com.ctc.wstx.exc.WstxUnexpectedCharException)
tdecom34        /config/BBPIHS.fmt                (IHS instance(s) clients setting has reached 1000 (MAX) threads)
ecswap33        /config/WFA.conf                /td/logs/WebLogs/WebFundsAdmin_33/System-ecswap33*.log
ecswap33        /config/WFA_tdsystem.fmt        (Error code: TD.SQL.4060 : SQLException - problems executing)
ecswap33        /config/WFA_tdsystem.fmt        Error code: TD.SQL.0 : The TCP\/IP connection to the host \*,port 3341 has failed., p


先谢谢了。
作者: Shell_HAT    时间: 2014-01-05 14:06
  1. sed -r 's/([^ \t]+)[ \t]+([^ \t]+)[ \t]+(.*)/\1,\2,"\3"/' a.txt > a.csv
复制代码

作者: elu_ligao    时间: 2014-01-05 14:25
  1. sed -nr 's/^([^[:space:]]+)(\s+)([^[:space:]]+)(\s+)/\1,\3,/p'

  2. awk '{printf $1","$2",";for(i=3;i<=NF;++i)printf $i;print a}'
复制代码
回复 1# fzhcl


   
作者: fzhcl    时间: 2014-01-06 00:21
本帖最后由 fzhcl 于 2014-01-06 00:27 编辑

回复 3# elu_ligao

两种代码都有同样的问题:最后一行变成多个列了。

ecswap33        /config/WFA_tdsystem.fmt        Error code: TD.SQL.0 : The TCP\/IP connection to the host \*        port 3341  has failed.         p

谢谢
作者: fzhcl    时间: 2014-01-06 00:27
回复 2# Shell_HAT


这个非常符合我的要求,谢谢

   
作者: fzhcl    时间: 2014-01-06 00:47
elu_ligao 发表于 2014-01-05 14:25
回复 1# fzhcl


参照Shell_HAT的code, 给$3 加上“” 就好了,
awk '{printf $1","$2",""\"";for(i=3;i<=NF;++i)printf $i;print a"\""}'




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2