You are using the +
quantifier from the Extended Regular Expression Syntax set, but sed
by default uses Basic Regular Expressions. So, you need to turn on ERE by adding the -E
flag:
sed -E 's/[0-9][0-9]+/9999/' file.cpp
or use the corresponding BRE construct
sed 's/[0-9]\{2,\}/9999/' file.cpp
which is more portable (as noted by @Stéphane Chazelas).
Note that this will modify any line that contains two or more consecutive digits by replacing that group with 9999
. If you want to ensure that only lines that conform to your example
if (counter==(1000)) {
are affected, I would recommend adding a suitable address specifier to make the matching more specific:
sed '/if (counter==([0-9]\{2,\}))/s/[0-9]\{2,\}/9999/' file.cpp
That way, the substitution would only be performed on lines that match if (counter==(two-or-more-digit-number))
.
The g
option doesn't seem necessary because in your input example, there is only one such digit group on the line.
In order to modify the file directly, most sed
implementations now understand the -i
flag for "in-place" modifications. Again, as correctly noted by @Stéphane Chazelas, if you use it in combination with other flags, be sure to make the ordering right, as -i
expects a suffix for creating a backup file (which may be left empty on GNU sed
, but is required in FreeBSD/MacOS implementations):
sed -i '' -E 's/.../.../'
will work on FreeBSD sed
sed -i -E 's/.../.../'
or sed -Ei 's/.../.../'
will work on GNU sed
sed -iE 's/.../.../'
will not work as the E
would be considered the backup suffix.
1000
, or that it's in parentheses, or that it occurs aftercount==(
? I'm asking because you probably don't want to change every number in the code, right?count==(
. Yes the idea is to eventually make a bash script where I will substitute the number with a variable "grep"ed from a another file.MaxCount=1000;
, because that would be much easier to identify with an edit, as relating to that specific instance of a number. Later, you might also consider making the value an external argument to the code.