Discussion:
[Help-bash] comma and missing
Val Krem
2018-03-19 01:29:08 UTC
Permalink
Hi all,
I have a file with  four variables, The variables may be separated by several white spaces .  All records may not have the four variables (missing variables).  Example of data is shown below.

Var1  Var2    var3       var4           
ZZ2  117222807   72721821  117763696
ZJ4   300341838   3417558                  
ZJ8   114816452 3436681   67107510
ZJ0   753410012  
ZJ3  127607528 67453049  67072875
Z14

In the example  in record 2  var4 is missing, in  record 4, var3 and var4 are missing  and in record 6  var2, var3 and var4  are missing.

I want to produce a comma separated , accounting the missing variables too and the  output   should be as shown below.

Var1,Var2,var3,var4           
ZZ2,117222807,72721821,117763696
ZJ4,300341838,3417558,                  
ZJ8,114816452,3436681,67107510
ZJ0,753410012,,
ZJ3,127607528,67453049,67072875
Z14,,,

I tried this
sed 's/ \{1,\}/,/g'  file1, but I did not get whet I wanted.


Any help is highly appreciated in advance
Pierre Gaston
2018-03-19 07:27:44 UTC
Permalink
Post by Val Krem
Hi all,
I have a file with four variables, The variables may be separated by
several white spaces . All records may not have the four variables
(missing variables). Example of data is shown below.
Var1 Var2 var3 var4
ZZ2 117222807 72721821 117763696
ZJ4 300341838 3417558
ZJ8 114816452 3436681 67107510
ZJ0 753410012
ZJ3 127607528 67453049 67072875
Z14
In the example in record 2 var4 is missing, in record 4, var3 and var4
are missing and in record 6 var2, var3 and var4 are missing.
I want to produce a comma separated , accounting the missing variables too
and the output should be as shown below.
Var1,Var2,var3,var4
ZZ2,117222807,72721821,117763696
ZJ4,300341838,3417558,
ZJ8,114816452,3436681,67107510
ZJ0,753410012,,
ZJ3,127607528,67453049,67072875
Z14,,,
I tried this
sed 's/ \{1,\}/,/g' file1, but I did not get whet I wanted.
Any help is highly appreciated in advance
awk '{printf "%s,%s,%s,%s\n",$1,$2,$3,$4}' file1

Loading...