Search code examples
bashsedechobc

sed pattern parts as input for other bash function


I'm trying to replace floating-point numbers like 1.2e + 3 with their integer value 1200. For this I use sed in the following way:

 echo '"1.2e+04"' | sed "s/\"\([0-9]\+\.[0-9]\+\)e+\([0-9]\+\)\"/$(echo \1*10^\2|bc -l)/"

but the pattern parts \1 and \2 doesn't get evaluated in the echo.

Is there a way to solve this problem with sed? Thanks in advance


Solution

  • Within the double quotes, \1 and \2 are interpreted as literal 1 and 2. You need to put additional backslashes to escape them. In addition, $(command substitution) in sed replacement seems not to work when combined with back references. If you are using GNU sed, you can instead say something like:

    echo '"1.2e+04"' | sed "s/\"\([0-9]\+\.[0-9]\+\)e+\([0-9]\+\)\"/echo \"\\1*10^\\2\"|bc -l/;e"
    

    which yields:

    12000.0
    

    If you want to chop off the decimal point, you'll know what to do ;-).