I am just trying to replace several arithmetic expressions inside a script file, which I cannot seem to find a simple solution for on the web. Adapting this answer did not do the trick.
Suppose I have the following, very simple file test.py
:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
u1 = [13 - 1];
u2 = [ 9 - 1];
print(u2)
I already tried (from the bash):
awk '{while(match($0, /([0-9]+)\-([0-9]+)/, m)) sub(/([0-9]+)\-([0-9]+)/, m[1] - m[2]) } 1' test.py
which does not seem to do anything. The following command
perl -pe 's/([\d+)\-(\d+])/$1-$2/ge' test.py
gives
#!/usr/bin/env python3
# 0*0 coding: utf08 0*0
u1 = [13 0 1];
u2 = [ 9 0 1];
print0u20
so not really what I want, not even valid code.
Inside Vim, I selected the text in visual (block) mode and piped it into bc
or bc -l
using !
, which gives
(standard_in) 1: syntax error
though it used to work if the whole line just was 13 - 1
, instead of u1 = [13 - 1];
Does anyone have a suggestion of a working solution which I could just apply on the whole file, which would replace any occurrence of [n - 1]
, [nn - 1]
and [ n - 1]
by the corresponding arithmetic result, retaining the square brackets?