Of course in Vim you have <C-a> to increment a number.

Is this POSIX specified?

How can I increment (or decrement) a number portably, such as in a scripted edit with ex?

Even if the answer is just "Use an external filter," what would be the best POSIX-specified tool for this job?

Example specific requirement:

  1. Increment the number found in the final field of line 1 by 1.
  2. Decrement the number found in the final field of line 2 by 1.

Example input:

Here is    a    number: 5
Here is another number: 2

Example output:

Here is    a    number: 6
Here is another number: 1

<C-a> and <C-x> being normal mode commands, they are not really expected to work in ex which doesn't have normal mode. Furthermore, those commands are not defined in the POSIX standard, either for vi or for ex.

As for a portable solution, you should probably write an awk script that would contain something like the following:

'{gsub( "number: \d", "number: " $5++ ); print }' foo
  • 2
    With the default FS, modifying a field will nuke the extra spaces seen in the original record, when the record is re-computed for output. You might be better off doing; awk -F': ' 'NR == 1{$NF++} NR == 2{$NF--}1'.
    – muru
    Apr 9 '16 at 7:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.