Joan Serrano
Joan Serrano

Reputation: 71

Delete decimals of a specific columns with sed

I am working with a csv file and I want to truncate the numbers with decimals of a specific column. Three of the lines are:

123;rr;2;RRyO, chess mobil;pio;25.766;1;0;24353;21.876;;S

1243;rho;9;RpO, chess yext cat;downpio;67.98;1;0;237753;25.346;;S

1243;rho;9;RpO, chess yext cat;pio;73;1;0;237753;25.346;;S

And I want this output:

123;rr;2;RRyO, chess mobil;pio;25;1;0;24353;21.876;;S

1243;rho;9;RpO, chess yext cat;downpio;67;1;0;237753;25.346;;S

1243;rho;9;RpO, chess yext cat;pio;73;1;0;237753;25.346;;S

I have tried thies code:

sed  -e '/^.\+pio$/,/^\..\*;[[:digit:]];[[:digit:]];.\*;.\*;.\*;.\*[[:space:]]$/d' data.csv

but doesnt work... Any suggestion, please?

Upvotes: 3

Views: 496

Answers (4)

potong
potong

Reputation: 58430

This might work for you (GNU sed):

sed -E 's/([0-9]+)(\.[0-9]+)?|([^;]+)/\1\3/6' file

Fields may be numbers, numbers with a decimal or not numbers.

On the sixth such field return the number part only if it exists.

Upvotes: 0

RavinderSingh13
RavinderSingh13

Reputation: 133528

With your shown samples, please try following. You could simple convert floating points to digits by awk's sprintf function.

awk 'BEGIN{FS=OFS=";"} {$6=sprintf("%d",$6)} 1' Input_file

From man page of awk:

sprintf(fmt, expr-list) Print expr-list according to fmt, and return the resulting string.

Upvotes: 3

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626870

You can use

sed 's/^\(\([^;]*;\)\{5\}[0-9]*\)[^;]*/\1/' data.csv

Details:

  • ^ - start of string
  • \(\([^;]*;\)\{5\}[0-9]*\) - Group 1 (\1):
    • \([^;]*;\)\{5\} - five occurrences of any zero or more chars other than ; and a ;
    • [0-9]* - zero or more digits
  • [^;]* - zero or more chars other than ;.

See the online demo:

s='123;rr;2;RRyO, chess mobil;pio;25.766;1;0;24353;21.876;;S
1243;rho;9;RpO, chess yext cat;downpio;67.98;1;0;237753;25.346;;S
1243;rho;9;RpO, chess yext cat;pio;73;1;0;237753;25.346;;S'
sed 's/^\(\([^;]*;\)\{5\}[0-9]*\)[^;]*/\1/' <<< "$s"

Output:

123;rr;2;RRyO, chess mobil;pio;25;1;0;24353;21.876;;S
1243;rho;9;RpO, chess yext cat;downpio;67;1;0;237753;25.346;;S
1243;rho;9;RpO, chess yext cat;pio;73;1;0;237753;25.346;;S

Upvotes: 1

Beta
Beta

Reputation: 99094

I haven't fully reverse-engineered you sed command, but this seems to work:

sed 's/\(.*pio;[0-9]*\)\.[0-9]*/\1/' data.csv

Upvotes: 2

Related Questions