3

tl;dr

I want to add a 0 at the end of the first backreference (\1) from a grep search. How can I differentiate this from the tenth backreference (\10).


Using in , I want to replace a part of a string with a part of that part of a string and a zero.

For example, find and replace this part of a string:

195.22.126.x

in this string:

195.22.126.x - - [13/Jul/2018:19:16:49 -0200] "GET /file.txt HTTP/1.1" 301 243

with part of that part of a string and a zero:

195.22.126.0

If I wanted to replace the "x" at the end of that part of a string with a "y", the code would look like this:

Find:
^(\d+\.\d+\.\d+\.)x

Replace:
\1y

But if I want to replace the "x" with a "0" (zero), the program tries to extract the tenth match, instead of appending a zero to the first match, because \10 looks like "tenth match" to it, not like "first match and a zero".

So how do I append a zero to a grep match?


Please note that I cannot simply replace "x" with "0", because there are other "x"s in the string. Therefore I have to match the correct part of the string.

Community
  • 1
  • 1

1 Answers1

1

EDIT Do this:

Find:
^(\d+\.\d+\.\d+\.)x

Replace:
\010

From the manual:

If more than two decimal digits follow the backslash, only the first two are considered part of the backreference. Thus, “\111” would be interpreted as the 11th backreference, followed by a literal “1”. You may use a leading zero; for example, if in your replacement pattern you want the first backreference followed by a literal “1”, you can use “\011”. (If you use “\11”, you will get the 11th backreference, even if it is empty.)


Well, if this is the actual string you want to work with, there’s a simple solution: just move the last dot out of the group.

Find:
^(\d+\.\d+\.\d+)\.x

Replace:
\1.0

If you want to replace something else where this workaround doesn’t work, another simple workaround would be like this:

First find:
^(\d+\.\d+\.\d+\.)x

First replace:
\1zzfoobarzz0

Second find:
zzfoobarzz

Second replace:
(empty)

Where zzfoobarzz is some such weird string that appears nowhere in the file. Ugly but workable.

Another idea would be to use a lookbehind assertion to match 195.22.126., leaving it out of the group. It would not be replaced, that way.

Tom Zych
  • 12,329
  • 9
  • 33
  • 51
  • You are right about moving the dot out of the group. I didn't think of that when I came up with my example. But your edit gave me what I wanted (`\010`). Thank you for that. And for those who wonder: That's the BBEdit User Manual. –  Jul 14 '18 at 16:08