How do I add a comma as my delimiter for the output of awk
> 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
> 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
. Hence there will be no 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. 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.