bash Sed - 将负数转换为正数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8419384/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 01:09:07  来源:igfitidea点击:

Sed - convert negative to positive numbers

bashsed

提问by frodo

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])\ //p'

but it is not working as it outputs:

但它不工作,因为它输出:

3245 -45 -72

3245 -45 -72

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

我想通过使用 \1\2 我会得到正数?

Where am I going wrong ?

我哪里错了?

回答by Prisoner

Why not just remove the -'s?

为什么不删除 - 的?

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

回答by Dan Fego

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

我的第一个想法是不要使用 sed,如果你不需要的话。awk 可以理解它们是数字并因此转换它们:

echo "-32 45 -45 -72" | awk -vRS=" " -vORS=" " '{ print ( < 0) ? ( * -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.

-vRS 将“记录分隔符”设置为空格,-vORS 将“输出记录分隔符”设置为空格。然后它简单地检查每个值,看它是否小于 0,如果是,则乘以 -1,如果不是,则只打印数字。

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

在我看来,如果你不做到用sed,这是更“正确”,因为它把相同的数字编号。

回答by potong

This might work for you:

这可能对你有用:

 echo "-32 45 -45 -72" | sed 's/-\([0-9]\+\)//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.

  1. 您只进行一次替换(否g

  2. 您的替代品末尾没有空格。

  3. 最后一个数字后面没有空格,所以它总是会失败。

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

这也可以工作,但不太优雅(并且仅适用于 2 位数):

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

Of course for this example only:

当然仅针对此示例:

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

回答by Nik K

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 Expansionto remove the minus sign:

您正在像处理字符串一样处理数字。更合适的是将数字存储在数组中并使用内置的Shell 参数扩展来删除减号:

    [~] $ # 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
    [~] $