frodo
frodo

Reputation: 1063

Sed - convert negative to positive numbers

I am trying to convert all negative numbers to positive numbers and have so far come up with this

echo "-32 45 -45 -72" | sed -re 's/\-([0-9])([0-9])\ /\1\2/p'

but it is not working as it outputs:

3245 -45 -72

I thought by using \1\2 I would have got the positive number back ?

Where am I going wrong ?

Upvotes: 2

Views: 10829

Answers (4)

Nik K
Nik K

Reputation: 21

You are dealing with numbers as with a string of characters. More appropriate would be to store numbers in an array and use built in Shell Parameter Expansion to remove the minus sign:

    [~] $ # Creating and array with an arbitrary name:
    [~] $ array17=(-32 45 -45 -72)
    [~] $ # Calling all elements of the array and removing the first minus sign:
    [~] $ echo ${array17[*]/-}
    32 45 45 72
    [~] $

Upvotes: 2

potong
potong

Reputation: 58381

This might work for you:

 echo "-32 45 -45 -72" | sed 's/-\([0-9]\+\)/\1/g'

Reason why your regex is failing is

  1. Your only doing a single substitution (no g)

  2. Your replacement has no space at the end.

  3. The last number has no space following so it will always fail.

This would work too but less elegantly (and only for 2 digit numbers):

 echo "-32 45 -45 -72" | sed -rn 's/-([0-9])([0-9])(\s?)/\1\2\3/gp'

Of course for this example only:

 echo "-32 45 -45 -72" | tr -d '-'

Upvotes: 3

Dan Fego
Dan Fego

Reputation: 14004

My first thought is not using sed, if you don't have to. awk can understand that they're numbers and convert them thusly:

echo "-32 45 -45 -72" | awk -vRS=" " -vORS=" " '{ print ($1 < 0) ? ($1 * -1) : $1 }'

-vRS sets the "record separator" to a space, and -vORS sets the "output record separator" to a space. Then it simply checks each value, sees if it's less than 0, and multiplies it by -1 if it is, and if it's not, just prints the number.

In my opinion, if you don't have to use sed, this is more "correct," since it treats numbers like numbers.

Upvotes: 4

Prisoner
Prisoner

Reputation: 27618

Why not just remove the -'s?

[root@vm ~]# echo "-32 45 -45 -72" | sed 's/-//g'
32 45 45 72

Upvotes: 12

Related Questions