0

I have a file whose contents look like this.

2,0,-1.8433679676403103,0.001474487996447893
3,1,0.873903837905657,0.6927701848899038
1,1,-1.700947426133768,1.5546514434152598

CSV with four columns whose third and last columns are floats.

I want to get rid of the whole part of the numbers (including the sign) and keep only the three first digits of the decimal part so that the above sample would become

2,0,843,001
3,1,873,692
1,1,700,554

How can I do this?

2
  • 2
    What have you tried already? I would recommend you read up on SED, AWK, and other text processing commands to see what they are capable of.
    – 0xSheepdog
    May 29 '19 at 17:51
  • @JeffSchaller The signs are included in the whole part. I made it explicit, thanks.
    – Text
    May 29 '19 at 18:40
2
sed 's/-\{,1\}[0-9]*\.\([0-9]\{,3\}\)[0-9]*/\1/g' file

This looks for strings starting with an optional - followed by any number of digits followed by a period, followed by any number of digits out of which it will pick the first three.

Another way is to replace [0-9] with [[:digit:]] as

sed 's/-\{,1\}[[:digit:]]*\.\([[:digit:]]\{,3\}\)[[:digit:]]*/\1/g' file
1

Using awk:

awk -F[,.] '{print $1","$2","substr($4,1,3)","substr($6,1,3)}' file

Where -F used to set the FS values to comma , and dot .

substr will print the 3 digits required after the dot.

1

awk? Why not python?

import csv
filename = <yourfilenamehere>

for line in list(csv.reader(open(filename, 'r'))):
    extra = [str(int((abs(float(num)) % 1) * 1000)).zfill(3) for num in line[2:]]
    print(*(line[:2] + extra), sep=',')
2
  • Because this is Unix.SE.
    – Text
    May 29 '19 at 18:41
  • 1
    Python runs in *nix systems. May 29 '19 at 18:42
1

Using sed:

sed -E 's/(^|,)[^\.][^,]*\.(...)[^,]*/\1\2/g' infile
1
  • 1
    note: I give it to you to find out how does it works as a practice. May 29 '19 at 17:56
1
$ perl -lne 'print join " ", /\.\K(...)/g' file
0

I tried by below awk method

command

awk -F "," 'OFS=","{print $1,$2,substr($3,4,3),substr($4,3,3) filename

output

2,0,843,001
3,1,739,692
1,1,700,554
1
  • It seems like there's some code missing? there's an unbalanced single quote and open curly brace.
    – Jeff Schaller
    Jun 3 '19 at 17:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.