Addition with 'sed'
If you honestly want to use sed, then this is the way to go:
s/[0-9]/<&/g
s/0//g; s/1/|/g; s/2/||/g; s/3/|||/g; s/4/||||/g; s/5/|||||/g; s/6/||||||/g
s/7/|||||||/g; s/8/||||||||/g; s/9/|||||||||/g
: tens
s/|</<||||||||||/g
t tens
s/<//g
s/+//g
: minus
s/|-|/-/g
t minus
s/-$//
: back
s/||||||||||/</g
s/<\([0-9]*\)$/<0\1/
s/|||||||||/9/; s/||||||||/8/; s/|||||||/7/; s/||||||/6/; s/|||||/5/; s/||||/4/
s/|||/3/; s/||/2/; s/|/1/
s/</|/g
t back
Input:
1+2
100+250
100-250
Output:
3
350
-150
Your mission, should you choose to accept it, is to implement multiplication.
sed
isn't the best option here, it doesn't do arithmetics natively (see Increment a number for how you could possibly do it though). You could do that with awk
:
$ echo 12 | awk '{print $0+3}'
15
The best piece of code to use will depend on the exact format of your input and what you want/need to do if it is not numeric, or contains more than one number, etc.
You could also do this only with bash
:
$ echo $(( $(echo 12) + 3 ))
or using expr
in a similar fashion.
I tried to accept your challenge @Richter, this is what I did using part of your code:
sed 's/[0-9]/<&/g
s/0//g; s/1/|/g; s/2/||/g; s/3/|||/g; s/4/||||/g; s/5/|||||/g; s/6/||||||/g
s/7/|||||||/g; s/8/||||||||/g; s/9/|||||||||/g
: tens
s/|</<||||||||||/g
t tens
s/<//g
s/.*\*$/0/
s/^\*.*/0/
s/*|/*/
: mult
s/\(|*\)\*|/\1<\1*/
t mult
s/*//g
s/<//g
: back
s/||||||||||/</g
s/<\([0-9]*\)$/<0\1/
s/|||||||||/9/; s/||||||||/8/; s/|||||||/7/; s/||||||/6/; s/|||||/5/; s/||||/4/
s/|||/3/; s/||/2/; s/|/1/
s/</|/g
t back'
Input:
04*3
4*3
40*3
42*32
150*20
1*3
3*1
0*3
3*0
Output: all the correct results