how to add a charecter to a a number using "sed"?

Viewed 46

I got some output file, with a bug. I can't correct the source code, as it is not mine. The output is a table of numbers (14 columns, hundreds of rows) that look like "1.5398E+02" (format of X.XXXXE-YY ). The bug is that if the power has three digits, so the number look like "6.4492-137" (missing the "E"). I been told to run a "sed" with something like:

sed ' s/([0-9]\.[0-9]{4})-([0-9]{3})/\1E-\2/' model.txt > modelCorrect.txt

or maybe

sed ' s/([0-9]\.[0-9]{4})-([0-9]{3})/([0-9]\.[0-9]{4})-E([0-9]{3})' model.txt > modelCorrect.txt

But it doesn't work (sed: -e expression #1, char 39: invalid reference \2 on s' command's RHS or sed: -e expression #1, char 63: unterminated s' command). What am I doing wrong?

1 Answers

What am I doing wrong?

Just sed uses basic regular expressions (BREs). There, groups are written as \(...\). In your command there is no group, therefore you cannot use the reference \2.

To uses the "normal" extended regular expressions (EREs), use sed -E.

Other than that, you forgot to allow the + in your regex. And since your file has 14 columns, you may want to replace all matches in each line (using s/.../.../g) instead of just the first one.

Also, it probably is safer to match numbers with an arbitrary number of places. Why invest so much work into checking that the number has the format 1.4444-333 if you could just allow all numbers?

sed -E 's/([0-9])([-+][0-9]+)/\1E\2/g' <<< "6.4492-137 1.23+4"

prints 6.4492E-137 1.23E+4.

Related