user3499733
user3499733

Reputation: 13

Parsing data with awk

I make script for bash, but I need to help with one part of the script. I have values in this format

1,12, 3,70, 2,29
1,12, 3,78, 2,79
1,12, 3,27, 2,25

and I need to convert to this format

1.12 3.70 2.29
...
...

So I need to change comma for dot, and remove comma behind the number. I would like to do it with awk, but I have no idea how to do it. I can to parse it to 3 different file, and then split to one by command paste , but I would like to do it more effective. Thank you.

Upvotes: 1

Views: 106

Answers (7)

Jotne
Jotne

Reputation: 41456

An awk solution.

awk '{sub(/, /," ");gsub(/,/,".")}1' file
1.12 3.70. 2.29
1.12 3.78. 2.79
1.12 3.27. 2.25

Upvotes: 0

Juan Aguilera
Juan Aguilera

Reputation: 19

and this works, too. with the -e option you can add sed commands to the same instance:

sed -e s/", "/" "/g -e s/","/./g file1

Upvotes: 0

glenn jackman
glenn jackman

Reputation: 246807

awk -F, '{for (i=1; i<NF; i+=2) {printf "%s.%s", $i, $(i+1)}; print ""}' <<END
1,12, 3,70, 2,29
1,12, 3,78, 2,79
1,12, 3,27, 2,25
END
1.12 3.70 2.29
1.12 3.78 2.79
1.12 3.27 2.25

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174706

This sed command will also work,

sed 's/, / /g;s/,/./g' file
  • s/, / /g - replaces comma and space with space only.

  • s/,/./g - From the output of above command, it replaces , with .

Example:

$ echo "1,12, 3,70, 2,29" | sed 's/, / /g;s/,/./g'
1.12 3.70 2.29

Upvotes: 2

jaypal singh
jaypal singh

Reputation: 77105

Here is one using awk:

$ awk -F', ' '{$1=$1;gsub(/,/,".")}1' file
1.12 3.70 2.29
1.12 3.78 2.79
1.12 3.27 2.25
  • Set the Field Separator to comma and space.
  • Re-construct the entire line to allow fields to be separated by default OFS (space).
  • Using gsub replace the , to .

Upvotes: 2

H&#229;kon H&#230;gland
H&#229;kon H&#230;gland

Reputation: 40748

perl -pE '$_=~s/(\d+),(\d+)/$1.$2/g; $_=~s/,//g'

Upvotes: 2

anubhava
anubhava

Reputation: 785146

Using sed:

sed 's/,\([0-9]\)/.\1/g;s/,//g;' file
1.12 3.70 2.29
1.12 3.78 2.79
1.12 3.27 2.25

This is basically 2 phase approach where 1st operation replaces commas that are followed by digit with dot and 2nd operation just strips remaining commas.

Upvotes: 2

Related Questions