Leo Karti
Leo Karti

Reputation: 33

sed replacement for a negative number

hi I have a file containing numbers like

-640.68739330746

which I need to be changed to

(-  640.68739330746 )

I tried using this code

sed 's/(-[0-9]\d*(\.\d+))/\(\(-\s\s[0-9]\d*(\.\d+)\s\))\1\*\2//g'

but I am getting errors

Upvotes: 0

Views: 146

Answers (2)

RavinderSingh13
RavinderSingh13

Reputation: 133770

Could you please try following, in case you are ok with awk:

awk '{for(i=1;i<=NF;i++){if($i<0){$i="( "$i" )"}}} 1' Input_file


Let's say following is the Input_file(test data only):

cat Input_file
-640.68739330746 efuiweiuwv wnwvn 1213133 -0.9 -4 wvnwnvrnvn

When we run following code get following output then.

awk '{for(i=1;i<=NF;i++){if($i<0){$i="( "$i" )"}}} 1' Input_file
( -640.68739330746 ) efuiweiuwv wnwvn 1213133 ( -0.9 ) ( -4 ) wvnwnvrnvn

Upvotes: 0

RomanPerekhrest
RomanPerekhrest

Reputation: 92904

Use [0-9] character class to match digits and rely on regex captured groups (...):

sed -E 's/-([0-9]+\.[0-9]+)/(- \1 )/g' file

Sample test:

$ cat s1
-640.68739330746 -1.3 sdfsdf
-2.3333
$ sed -E 's/-([0-9]+\.[0-9]+)/( & )/g' s1
(- 640.68739330746 ) (- 1.3 ) sdfsdf
(- 2.3333 )

Upvotes: 3

Related Questions