Fixed width to CSV

痞子三分冷 提交于 2019-11-28 11:48:27

Using GNU awk for FIELDWIDTHS and \s/\S:

$ cat tst.awk
BEGIN { OFS="," }
FNR==1 { names=$0; next }
FNR==2 {
    FIELDWIDTHS=""
    while ( match($0,/\S+\s*/) ) {
        FIELDWIDTHS = (FIELDWIDTHS ? FIELDWIDTHS " " : "") RLENGTH
        $0 = substr($0,RSTART+RLENGTH)
    }
    $0 = names
}
{
    for (i=1;i<=NF;i++) {
        sub(/\s+$/,"",$i)
        printf "%s%s", $i, (i<NF?OFS:ORS)
    }
}

$ awk -f tst.awk file
Name,DOB,GENDER
JOHN DOE,19870130,M
MARY DOE,19850521,F
MARTY MCFLY,19790320,M

The above will work even if your first row contains spaces in the column names.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!