Math in sed/regexp expression
Math in sed/regexp expression
am 17.10.2007 17:00:49 von Kenneth Brun Nielsen
I have a file with numbers eg:
foo.txt:
1
24
1
2
Is it possible to make (simple) math on the numbers using sed?
I.e. adding 100 to the above numbers: "sed 's/\s*\(\d+\)\s*/
someFancyExpression(\1) /' foo.txt > bar.txt
Such that bar.txt will contain
101
124
101
102
Any suggestions? BTW, If other standard shell command tools are better
than sed, please enlighten me..
Re: Math in sed/regexp expression
am 17.10.2007 17:36:01 von Stephane CHAZELAS
2007-10-17, 15:00(-00), Kenneth Brun Nielsen:
> I have a file with numbers eg:
> foo.txt:
> 1
> 24
> 1
> 2
>
> Is it possible to make (simple) math on the numbers using sed?
>
> I.e. adding 100 to the above numbers: "sed 's/\s*\(\d+\)\s*/
> someFancyExpression(\1) /' foo.txt > bar.txt
>
> Such that bar.txt will contain
> 101
> 124
> 101
> 102
>
> Any suggestions? BTW, If other standard shell command tools are better
> than sed, please enlighten me..
awk would be better suited for the task:
awk '{print $1 + 100}'
But with sed:
sed 's/[^0-9]*\([0-9]*\).*/00\1/;s/.*\(..\)/1\1/'
--
Stéphane
Re: Math in sed/regexp expression
am 17.10.2007 17:55:44 von Kenneth Brun Nielsen
On Oct 17, 5:36 pm, Stephane CHAZELAS wrote:
> 2007-10-17, 15:00(-00), Kenneth Brun Nielsen:
> > Is it possible to make (simple) math on the numbers using sed?
> awk would be better suited for the task:
>
> awk '{print $1 + 100}'
Nice! Actually the complete assignment is a bit more complex, than the
one I stated (incl. several backreferences), but awk seems to be able
to do it all.
> But with sed:
>
> sed 's/[^0-9]*\([0-9]*\).*/00\1/;s/.*\(..\)/1\1/'
Ahh. Off course. Will only work for numbers below 100, but that's fine
for me.
Thanks a lot, St=E9phane
/Kenneth
Re: Math in sed/regexp expression
am 17.10.2007 19:39:58 von Cyrus Kriticos
Kenneth Brun Nielsen wrote:
> BTW, If other standard shell command tools are better
> than sed, please enlighten me..
[bash]
while read X; do echo $(($X+100));done < foo.txt
--
Best regards | Be nice to America or they'll bring democracy to
Cyrus | your country.
Re: Math in sed/regexp expression
am 19.10.2007 11:33:47 von ramesh.thangamani
On Oct 17, 10:39 pm, Cyrus Kriticos
wrote:
> Kenneth Brun Nielsen wrote:
> > BTW, If other standard shell command tools are better
> > than sed, please enlighten me..
>
> [bash]
>
> while read X; do echo $(($X+100));done < foo.txt
>
> --
> Best regards | Be nice to America or they'll bring democracy to
> Cyrus | your country.
With sed you can use sed 's/\([0-9]*\)/echo `expr 100 + \1`/' test.txt
| sh
but the command mentioned by St=E9phane using awk is better one.