Results 1 to 7 of 7
Thread: awk commas separation
|
Enjoy an ad free experience by logging in. Not a member yet? Register.
|
|
-
02-09-2013 #1
- Join Date
- Aug 2012
- Posts
- 24
awk commas separation
We have a file , "xxx.dat" like this
-50.4838 2.6147 0.0827
-49.1492 1.5374 0.1567
-48.1492 3.5374 2.0567
We try to transform them into csv format:
-50.4838,2.6147,0.0827
-49.1492,1.5374,0.1567
-48.1492,3.5374,2.0567
We have tried the followings. Both do not change the format from "xxx.dat" at all.
awk -F, '{print $1 $2 $3}' xxx.dat > xxx.csv
awk -F "\"*,\"*" '{print $1 $2 $3}' xxx.dat > xxx.csv
Could gurus tell us the reason? Thanks
-
02-09-2013 #2
- Join Date
- Jun 2012
- Posts
- 100
Why not use sed for that?
sed 's/ /,/g' xxx.dat > xxx.csv
-
02-09-2013 #3
awk works as well
Code:awk '{ print $1 "," $2 "," $3 }' < xxx.dat > xxx.csv
You probably want to add some regex to ensure data integrity.You must always face the curtain with a bow.
-
02-09-2013 #4
- Join Date
- Nov 2012
- Posts
- 335
hi,
Code:awk '{$1=$1}1' OFS=',' file
-
02-09-2013 #5
- Join Date
- Aug 2012
- Posts
- 24
Thanks Gurus. They work pretty well.
One more questions
We would like to print out formats like this:
91,-50.4838,2.6147,0.0827
135,-49.1492,1.5374,0.1567
138,-48.1492,3.5374,2.0567
Because this scrip is going to process many file again and again. We hope in each csv, the first line will will start with "91", the second line will start with "135", the third line starts with "138"...etc.
Here is the script
Y1='91'
Y2='135'
Y3='138'
for X in 1 2 3
do
Z="Y$X"
G=$(eval echo \$$Z)
awk '{ print "${G}", $1 "," $2 "," $3 }' < mmPBSA_e1_${time1}.dat > mmPBSA_e1_${time1}.csv
However, awk will print out something like this
${G} -50.4838,2.6147,0.0827
${G} -49.1492,1.5374,0.1567
${G} -48.1492,3.5374,2.0567
instead of
91,-50.4838,2.6147,0.0827
135,-49.1492,1.5374,0.1567
138,-48.1492,3.5374,2.0567
Could gurus kindly offer comments? Thanks.
Henry
-
02-09-2013 #6
- Join Date
- Nov 2012
- Posts
- 335
using eval should suggest you're doing it wrong.
you should always try to find another way. if you don't find one, try harder.
are your files always three lines?
Code:awk 'BEGIN{ Y[1]=95; Y[2]=135; Y[3]=138 }{$1=$1; print Y[NR],$0}' OFS=',' file
-
02-09-2013 #7
- Join Date
- Aug 2012
- Posts
- 24
Dear guru,
Thanks for your quick response. It works.
Not always. It might extend to N lines in the future. It's just temporarily three lines now.
Cheers,
Henry