Eniola
Eniola

Reputation: 133

How to use sed to extract negative number from a string

I need to extract a negative number from a file to another file, I already did this for a positive number, but I couldn't figure out how to do it for negative number.

sed -r 's/.* ([0-9]+\.*[0-9]*).*?/\1/' bob.txt > outfile.txt

bob.txt content:

outputVoltage.u900 = Opaque: Float: 27.000000 V

outputVoltage.u900 = Opaque: Float: -27.000000 V

The above code works perfectly for the positive value and not the negative value.

Inside outfile, I suppose to have:

27.000000

-27.000000

Upvotes: 2

Views: 783

Answers (2)

Enlico
Enlico

Reputation: 28406

If you want to stick to sed, you're almost there, the correct command being

sed -r 's/.* (-?[0-9]+\.*[0-9]*).*?/\1/' bob.txt > outfile.txt

I've only added -? which matches zero or one - characters.

Upvotes: 1

Jotne
Jotne

Reputation: 41456

What about just print the fifth field:

awk '{print $5}' bob.txt
27.000000
-27.000000

Or search for a string and print it:

awk '/outputVoltage/{print $5}' bob.txt
27.000000
-27.000000

Upvotes: 2

Related Questions