Ani*_*nil 0 regex shell perl awk sed
我正在尝试处理一个巨大的文件,如果数据需要修改结构.我的文件有117列,但为了简单起见,让我们假设我有一个包含10列的文件示例文件:
col1, col2, col3, col4, col5, col6, col7, col8, col9, col10
1,2,3,4,5,6,7,8,9,10
Run Code Online (Sandbox Code Playgroud)
我现在想要 - 包括col6到col10的列名和列值 - 并用'|'替换分隔符 从col6到col10为整个文件
要求的输出
1,2,3,4,5,col6:6|col7:7|col8:8|col9:9|col10:10
Run Code Online (Sandbox Code Playgroud)
这有可能吗?我是regex/awk的新手.有人可以帮忙吗
PS:一旦处理完数据,我就试图从'|'中清除掉零 分隔栏...
So, if the data is 1,2,3,4,5,6,0,8,0,10
I would convert it to 1,2,3,4,5,col6:6|col7:0|col8:8|col9:0|col10:10
and then remove the zero's 1,2,3,4,5,col6:6|col8:8|col10:10
so input: 1,2,3,4,5,6,0,8,0,10
Desired output: 1,2,3,4,5,col6:6|col8:8|col10:10
Run Code Online (Sandbox Code Playgroud)
你可以使用这个awk:
awk -F ', *' 'NR==1{for (i=1; i<=NF; i++) hdr[i]=$i; next}
{for (i=1; i<=NF; i++) printf "%s%s", ((i>5)?hdr[i] ":":"") $i,
((i<NF)? ((i>5)?"|":",") : ORS)}' file
Run Code Online (Sandbox Code Playgroud)
输出:
1,2,3,4,5,col6:6|col7:7|col8:8|col9:9|col10:10
Run Code Online (Sandbox Code Playgroud)
hdr 是何时保存标题列名称的关联数组 NR==1
更新:根据评论,OP希望跳过零值的列.您可以使用:根据评论,OP希望跳过零值的列.您可以使用:
awk -F ', *' 'NR==1{for (i=1; i<=NF; i++) hdr[i]=$i; next}
{for (i=1; i<=NF; i++) if ($i>0) printf "%s%s", ((i>5)?hdr[i] ":":"") $i,
((i<NF)? ((i>5)?"|":",") : ORS)}' file
Run Code Online (Sandbox Code Playgroud)