Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

conversion

Status
Not open for further replies.

krava

Programmer
Jun 4, 2007
48
YU
Hi,

I would like to have bash function that would convert space-separated data table into comma-separated one. This is what I put together so far

function dat2csv() {
for fl in `find -type f -name "$1" -print`; do
#echo $fl;
bNm="$(basename $fl .dat)"; # echo $bNm;
of=$bNm".csv"; #echo $of;
echo $fl ">" $of;
sed 's/ /,/g' $fl > $of
done
}

This works but if I have table that is separated by 2 spaces than it fails. How to make this function useful in genaral case (separated by 1, 2 ... n spaces)?


thx
p.
 
Hi

So you want to transform like 1 space -> 1 comma, 2 space2 -> 1 comma, ..., n spaces -> 1 comma ? What happens if 2 spaces mean 2 separators and the data between them is empty string ? Anyway :
Code:
sed 's/ [red]\+[/red]/,/g' $fl > $of

[gray]# or[/gray]

sed 's/ [red][highlight #fee] [/highlight]*[/red]/,/g' $fl > $of

Feherke.
 
there is no empty string ... I am lucky I guess :)

this is what happens with sed 's/ \+/,/g' $fl > $of

119.77698 420.95663
4.93927 2.84465
24.99672 84.16383
.......... ........

converts to:

,119.77698,420.95663
,4.93927,2.84465
,24.99672,84.16383
...................

and with sed 's/ */,/g' $fl > $of to:

,1,1,9,.,7,7,6,9,8,4,2,0,.,9,5,6,6,3,
,4,.,9,3,9,2,7,2,.,8,4,4,6,5,
,2,4,.,9,9,6,7,2,8,4,.,1,6,3,8,3,
..............................

What should be done?

 
what about this ?
sed 's!^ \+!!;s! \+!,!g' $fl > $of

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
or with awk:

awk '{
for (i=1;i<NF;i++)
printf "%s,", $i
print $NF
}' /path/to/inputfile


HTH,

p5wizard
 
Hi

krava said:
and with sed 's/ */,/g' $fl > $of to:
Maybe the pink background I used to emphasize the second space character was too light... You have to put two spaces in front of the asterisk ( * ).

Anyway, now you have versions which remove the leading separator, go with one of those.

Feherke.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top