Home > Mobile >  How to properly use the /e command from GNU sed
How to properly use the /e command from GNU sed

Time:09-06

I am trying to wrap my head around the /e command from GNU sed. It turns out that it is very tricky to get it work as expected.

(Please note that in the examples, below I am not claiming that sed is the perfect tool for the job, but it serves just as a minimal example using /e command. So please kindly do not suggest any solution with AWK).

I have the following input file:

input.txt:

10.5 8 50.5-30.2 7 5
  • Assumptions:
  • No space/tab between the binary operators and the numbers.
  • Spaces/tabs are used ONLY as separators between expressions.

My attempt is to use the /e command to invoke bc commad to evaluate the expressions.

The expected output is:

18.5 20.3 12
sed -E "s/([^ \t] )/echo '\1' | bc /e" input.txt

But I am getting the following error:

File 50.5-30.2 is unavailable.

Questions:

  • Could someone please explain how does the command /e work? I have tried reading the manual over and over but I am still confused.
  • How can I fix the command above to get the expected output?

CodePudding user response:

You may use this gnu-sed command to fix it:

sed -E 's/[^ \t] /printf -- "$(echo & | bc) ";/ge' file

18.5 20.3 12

Or if you want output in different lines then:

sed -E 's/[^ \t] /echo & | bc;/ge' file

18.5
20.3
12

Terminator \n or ; after command is important to tell sed to run printf or echo once for each match.

CodePudding user response:

This might work for you (GNU sed,shell and bc):

echo '10.5 8 50.5-30.2 7 5' | sed 'y/ \t/;;/;s/.*/echo "&" | bc/e;y/\n/ /'

Convert echoed string into a bc input by translating spaces to ;'s.

Use the contents of the pattern space and echo it into bc via a pipeline.

Take the result of bc and translate newlines to spaces.

  • Related