简体   繁体   English

如何为 awk 的 output 添加逗号作为分隔符

[英]How do I add a comma as my delimiter for the output of awk

How do I add a comma as my delimiter for the output of awk如何为 awk 的 output 添加逗号作为分隔符

> cat file.csv
col1,col2,col3,col4
col1,col2,col3
col1,col2
col1
col1,col2,col3,col4,col5

This is my attempt:这是我的尝试:

> awk -F, 'BEGIN{FS=OFS=","} {print $1 $2}' file.csv
    col1col2
    col1col2
    col1col2
    col1
    col1col2
    >

What I want is this我要的是这个

col1,col2
col1,col2
col1,col2
col1,
col1,col2

Below is just for my ref:以下仅供我参考:

> awk -F, '{print $0}' file.csv
col1,col2,col3,col4
col1,col2,col3
col1,col2
col1
col1,col2,col3,col4,col5

> awk -F, '{print $1}' file.csv
col1
col1
col1
col1
col1

> awk -F, '{print $1 $2}' file.csv
col1col2
col1col2
col1col2
col1
col1col2

The statement print $1 $2 prints one output field, the concatenation of $1 and $2 .语句print $1 $2打印一个output 字段,即$1$2的串联。 Hence there will be no OFS output.因此不会有OFS output。

What you're looking for is print $1, $2 which prints two distinct fields, and will therefore have the OFS inserted between them.您正在寻找的是print $1, $2打印两个不同的字段,因此将在它们之间插入OFS You can see the difference in the following transcript:您可以在以下成绩单中看到差异:

pax@styx:~> echo "1 2" | awk 'BEGIN{OFS="-xyzzy-"}{print $1 $2}'
12
pax@styx:~> echo "1 2" | awk 'BEGIN{OFS="-xyzzy-"}{print $1, $2}'
1-xyzzy-2

if you actually want that trailing "," :如果你真的想要那个尾随的","

 mawk NF=2 FS=, OFS=,
col1,col2
col1,col2
col1,col2
col1,
col1,col2

...without the trailing "," : ...没有尾随的","

 gawk 'NF < 2 || NF = 2' FS=, OFS=,
col1,col2
col1,col2
col1,col2
col1
col1,col2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM