1

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

Paul R
  • 208,748
  • 37
  • 389
  • 560
sakhunzai
  • 13,900
  • 23
  • 98
  • 159
  • Using hard quotes (`'`) is preventing `$(echo "\1+16"|bc)` from being expanded. – Paul R Jan 26 '15 at 11:34
  • @PaulR what is work around then – sakhunzai Jan 26 '15 at 11:40
  • 1
    You just need to fix your quoting, i.e. don't use hard quotes around stuff you want to be expanded. – Paul R Jan 26 '15 at 11:41
  • would you add a fixed version as answer ? When I remove quotes it gives me `-bash: syntax error near unexpected token `('` error – sakhunzai Jan 26 '15 at 11:52
  • It looks like this won't work even when you fix the quoting, since you can't do arithmetic in sed - see http://stackoverflow.com/questions/2687009/sed-awk-or-other-one-liner-to-increment-a-number-by-1-keeping-spacing-character + consider using awk instead. – Paul R Jan 26 '15 at 11:54
  • I got the idea from this http://stackoverflow.com/questions/14348432/how-to-find-replace-and-increment-a-matched-number-with-sed-awk – sakhunzai Jan 26 '15 at 11:55
  • In the question you were looking at they were using GNU sed - since you're using OS X you don't have this (which is also why the `-r` option doesn't work). Use awk or perl - it will be much easier. – Paul R Jan 26 '15 at 11:58
  • It's not the `-r` so much as the `/e` modifier flag. – tripleee Jan 26 '15 at 12:01

3 Answers3

2

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
Jotne
  • 40,548
  • 12
  • 51
  • 55
1

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'
tripleee
  • 175,061
  • 34
  • 275
  • 318
1

Difficult with sed, but here's a perl solution:

$ echo "abc top: 234px" | perl -pe 's/(\d+)/16 + $1/ge'
abc top: 250px
Paul R
  • 208,748
  • 37
  • 389
  • 560