Issue
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?
Solution
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.
Answered By - anubhava Answer Checked By - Willingham (WPSolving Volunteer)