+ Reply to Thread
Results 1 to 5 of 5

Math in sed/regexp expression

  1. Math in sed/regexp expression

    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..


  2. Re: Math in sed/regexp expression

    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

  3. Re: Math in sed/regexp expression

    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éphane

    /Kenneth


  4. Re: Math in sed/regexp expression

    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.

  5. Re: Math in sed/regexp expression

    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éphane using awk is better one.


+ Reply to Thread