Hello!

Em seg., 8 de jun. de 2020 às 08:37, Freeman Gilmore <
freeman.gilm...@gmail.com> escreveu:

> If the string is   "A ... B ... " , using Regexp Functions is it
> possible, if 'A' matches [-] then 'B' would be replaced by "C"?    'A'
> is first in the string.  Position of B is not constant.and may not be
> there.
>

Can you provide a little more context of what you are trying to do and what
this has to to with lilypond? What tools are you using to find and replace
strings using regex?

Anyway, here is a solution of what I _think_ is your problem using 'sed' in
a Linux terminal. Suppose we have a file regex_test.txt with the following
content:

----
- I want to replace [B] for [C]
- But don't want to replace anything here
This line has [B], but doesn't start with the dash. So nothing will be
replaced here.
---

The following command should replace the first [B] with [C]:

sed '/^-.*\[B\]/s/\[B\]/[C]/' regex_test.txt

---- output:
- I want to replace [C] for [C]
- But don't want to replace anything here
This line has [B], but doesn't start with the dash. So nothing will be
replaced here.
----

If you are happy with the result, you can write direclty to the file using
the -i flag

sed -i '/^-.*\[B\]/s/\[B\]/[C]/' regex_test.txt

Explanation:

We provide to sed a patern with four parts separated by a slash '/'. The
first part

^-.*\[B\]

means a line starting (^) with a dash followed by anything (.*) and
containing a [B] in it. We had to prefix the brackets [ and ] with
backslashes to tell sed these are literally the caracters [ and ], because
these are special characters in regex. The other parts

s/\[B\]/[C]

mean substitute (the command s) the element [B] (notice the backslashes
here again) with the element [C] (no backslashes needed here).

Finally, of course, we pass to sed the file to do the operation.

Hope that helps!
Caio

Reply via email to