Reputation: 14500
I am trying to do simple find replace digit while adding a value but failing to do so under Mac OS X, e.g.
echo "abc top: 234px" |sed -E 's/top:[[:space:]]*([0-9]+)/echo $(echo "\1+16"|bc)/g'
which should output: "abc top: 250px"
Instead it outputs: abc echo $(echo "234+16"|bc)px
Upvotes: 1
Views: 493
Reputation: 41460
Here is an awk
echo "abc top: 234px" | awk '$NF=$NF+16"px"'
abc top: 250px
Some more robust with search for top
:
echo "abc top: 234px" | awk '/top:/ {$NF=$NF+16"px";print}'
abc top: 250px
Here you do not need the format prefix px
:
echo "abc top: 234px" | awk 'sub(/[0-9]+/,$NF+16)'
abc top: 250px
or
echo "abc top: 234px" | awk '/top:/ {sub(/[0-9]+/,$NF+16);print}'
abc top: 250px
Upvotes: 2
Reputation: 213200
Difficult with sed, but here's a perl solution:
$ echo "abc top: 234px" | perl -pe 's/(\d+)/16 + $1/ge'
abc top: 250px
Upvotes: 1
Reputation: 189936
You cannot refer back to the back-reference using an external command -- when echo | bc
is evaluated (once you fix the quoting so that they are evaluated at all in the first place), the sed
script has not yet been parsed.
What you can do is switch to a tool which allows for arithmetic on captured values.
echo "abc top: 234px" |
perl -pe 's/(top:\s*)(\d+)/ sprintf("%s%i", $1, 16+$2)/ge'
Upvotes: 1