Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do I convert numeric from 123.45- to -123.45 1

Status
Not open for further replies.

Tison

Programmer
May 12, 1999
216
CH
I have a flat text file which contains a column of numbers.
The format of the number is nnnn.nn- (with minus sign at end).
I need to put the minus sign before the number ie -nnnn.nn

How do I do that ?
 
This script works:

sed -f changeminus minus > newfile
for number in `cat newfile`
do
echo '-'$number >> newfile1
done

'changeminus' is a sed script containing the following line:

 
Oops sorry - touch of premature submitting there!
:~/


Anyway, to continue. The sed script consists of one line as follows:

s/-//g

The word 'minus' should be replaced by your real filename.

Hope this helps. No doubt there's a far easier way to do this in awk, and no doubt someone will be along soon to explain how! Cheers.
 
This does not work because I have a mixture of positiove and negative numbers in the file.
 
Ah, now you didn't say that did you ;-)? Are the positives in a similar format at the moment (ie nnnn.nn+) or do they have no sign at all? Regards.
 
They have no sign
AND
they are not the only column in each record.
What do you think of this ;
while read CD CRN FUND AMT
do
if ( echo $AMT | grep -c "-" > /dev/null )
then
AMT=`echo $AMT | sed s/-// `
AMT=`echo "-"$AMT`
fi
echo "$CD \t $CRN \t $FUND \t $AMT" >> outfile

done < infile
 
Very quickly - I created a data file called x which contains

FIELD1 123.45- 123
abdc 12.45 123
abcd 1.20- 123

I created the following file called x.sh

while read -r f1 f2 f3
do
echo $f1&quot;\t\c&quot;
LENGTH=`expr $f2 : &quot;.*&quot;`
LENGTH1=`expr $LENGTH - 1 `
SEP=`echo $f2 | cut -c$LENGTH`
if [ &quot;$SEP&quot; = &quot;-&quot; ]
then
REST=`echo $f2 | cut -c1-$LENGTH1`
echo $SEP$REST&quot;\t\c&quot;
else
echo $f2&quot;\t\c&quot;
fi
echo $f3 &quot;\n&quot;

done < x

execute x.sh , which reads a line at a time form the input file and checks the length of field 2 - see's if the last char is a -, if so print the - then the rest of the string - otherwise just print the string.

I'll put something together in awk also
 
You could also use the following sed command.

sed &quot;s/\([.0-9][.0-9]*\)-/-\1/g&quot; filename
CaKiwi
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top