If I have a simple text file, containing numbers of all negative value, how do I make all of those values positive?
So as an example, if test.txt has the following values:
-4
-5
-6
How do I make it so that the values are positive?
4
5
6
If I have a simple text file, containing numbers of all negative value, how do I make all of those values positive?
So as an example, if test.txt has the following values:
-4
-5
-6
How do I make it so that the values are positive?
4
5
6
So one of the MATHs rule if we multiply -1 with any number it will be changed to positive number of it's own(in case it is already negative), so similarly we could do it here as follows.
awk '{$0=$0 * -1} 1' Input_file
Hope this helps you.
So let's say your Input_fie has negative and positives both the values as follows.
cat file1
-4
-5
-6
7
Then following code we could use to avoid making everything negative(specially those which values are already positive).
awk '{$0=$0<0?$0 * -1:$0} 1' Input_file
Hope this helps you.
If your intention is to convert to positive only when the number is negative:
while read -r number; do
[[ number -lt 0 ]] && number=$((-1 * number))
echo $number
done < test.txt
It seems you don’t want to do any math, but simply remove all minus signs. In this case,
while read line; do echo ${line//-/}; done <test.txt
does the job without invoking external programs. It works also in the case that there is more than one number per line.
OK, I make the following assumptions:
#!/bin/bash
while read a
do
echo -1*$a | bc
done <test.txt