在尝试处理"mccli活动展示"(例如(,输出可能是这样的:
ID Status Error Code Start Time Elapsed End Time Type Progress Bytes New Bytes
---------------- ------------------------ ---------- -------------------- ----------- -------------------- ---------------- ----------------- ---------
9133910640004809 Completed w/Exception(s) 10020 2012-06-07 18:00 EDT 00h:53m:46s 2012-06-07 18:53 EDT Scheduled Backup 215 0.2%
9133914600006909 Completed 0 2012-06-08 05:00 EDT 00h:00m:04s 2012-06-08 05:00 EDT Scheduled Backup 0 0%
期望输出
ID, Status, Error Code, Start Time ,Elapsed ,End Time ,Type ,Progress Bytes ,New Bytes
----------------,------------------------, ---------- ,--------------------, -----------, --------------------, ---------------- ,----------------- ,---------
9133910640004809, Completed w/Exception(s), 10020, 2012-06-07 18:00 EDT, 00h:53m:46s ,2012-06-07 18:53 EDT, Scheduled Backup, 215 , 0.2%
9133914600006909, Completed , 0, ,2012-06-08 05:00 EDT, 00h:00m:04s ,2012-06-08 05:00 EDT, Scheduled Backup, 0 , 0%
代码I尝试
awk '!/---/{$1=x; sub(/,+$/,x)}1' OFS=,
但它不能作为每个空间的逗号
您发布的预期输出实际上没有意义(例如,0, ,
处的一个明显字段有两个逗号,有时逗号前有空格,有时逗号后有空格,有时候逗号后有and(,我认为您的示例输入不准确(例如215
和0.2%
看起来离得太近(,所以我猜是这样的,但对FIEDWIDTHS
和nextfile
使用GNU awk,这可能是你真正想做的:
$ cat tst.awk
NR == FNR {
if ( /^[- ]+$/ ) {
wids = length($1)
for ( i=2; i<=NF; i++ ) {
wids = wids " " length(FS $i)
}
nf = NF
nextfile
}
next
}
FNR == 1 {
FIELDWIDTHS = wids
OFS = ","
$0 = $0
}
NF { $nf = $nf }
{ print }
$ awk -f tst.awk file file
ID , Status , Error Code, Start Time , Elapsed , End Time , Type , Progress Bytes , New Bytes
----------------, ------------------------, ----------, --------------------, -----------, --------------------, ----------------, -----------------, ---------
9133910640004809, Completed w/Exception(s), 10020 , 2012-06-07 18:00 EDT, 00h:53m:46s, 2012-06-07 18:53 EDT, Scheduled Backup, 215 0.2%,
9133914600006909, Completed , 0 , 2012-06-08 05:00 EDT, 00h:00m:04s, 2012-06-08 05:00 EDT, Scheduled Backup, 0 , 0%
或:
$ cat tst.awk
NR == FNR {
if ( /^[- ]+$/ ) {
wids = length($1)
for ( i=2; i<=NF; i++ ) {
wids = wids " " length(FS $i)
}
nf = NF
nextfile
}
next
}
FNR == 1 {
FIELDWIDTHS = wids
OFS = ","
$0 = $0
}
NF {
$nf = $nf
$0 = gensub(/( +),/,",\1","g")
}
{ print }
$ awk -f tst.awk file file
ID, Status, Error Code, Start Time, Elapsed, End Time, Type, Progress Bytes, New Bytes
----------------, ------------------------, ----------, --------------------, -----------, --------------------, ----------------, -----------------, ---------
9133910640004809, Completed w/Exception(s), 10020, 2012-06-07 18:00 EDT, 00h:53m:46s, 2012-06-07 18:53 EDT, Scheduled Backup, 215 0.2%,
9133914600006909, Completed, 0, 2012-06-08 05:00 EDT, 00h:00m:04s, 2012-06-08 05:00 EDT, Scheduled Backup, 0, 0%