Inian Inian - 16 days ago 5
Bash Question

Using ex editor to increment a number following a pattern in a file

Am aware of how to use the

ex
editor in syntaxes like this answer to do minor editing of files in place.

For example, as mentioned in the answer, assuming I have a file content as below:-

$ cat input-file
patternGoingDown
foo
bar
foo
bar


Running a command using
ex
, like

$ printf "%s\n" '/patternGoingDown' 'd' '/foo' 'n' 'put' 'wq' | ex file
$ cat file
foo
bar
foo
patternGoingDown
bar


will move the pattern
patternGoingDown
after the second occurrence of
foo
. My requirement is to adopt a similar logic to increment a number after a pattern.

Example:-

$ cat input-file
The number is now number(60)


Is it possible to use the
ex
editor to increment the number from
60
to
61
like

$ cat input-file
The number is now number(61)


Though there is a ex-editor help page available, I can't figure out how to


  1. Parse the next character after search pattern,
    number
    in this case

  2. Increment to
    61
    which I can normally do via
    Ctrl+A
    when using
    vi
    editor.



I am aware there are other tools for this job, but I particularly need to use
ex
editor in the syntax I have mentioned.

Answer

This is tricky because Vim is not really suited to this. Awk is, but POSIX Awk does not do in place, so you have to use both:

ex -sc '%!awk "\
{\
  match(\$0, /[[:digit:]]+/)\
  j = substr(\$0, RSTART, RLENGTH)\
  sub(j, ++j)\
}\
1\
"' -cx file
Comments