arithmetics

Even to Odd converter

Here is an interesting problem: write a sed script to substitute every even number with the nearest odd number. I got this one from the list of the latest searches which bring the users to this site.
Let’s see how we can tackle this issue.

First of all, let me say that, for this type of tasks, I’d rather use awk because it has variables and strong and fast arithmetics capabilites. Here is how I’d do in awk:

$ echo "12 15 4 98 1123" | awk '{
for (i=1;i<=NF;i++)
if ($i ~ /^[0-9]*[02468]$/)
$i--
} 1'

The above command ignores numbers mixed with strings (i.e. foo12, 4bar2,etc.) and simply subtracts 1 from any even number (though you can easily add 1 by using $i++ in the place of $i–).