Using Raku (formerly known as Perl_6)
~$ raku -e 'put slurp.subst(:global, / \h+ <( "user.invoke()" \n \h+ "user.process(user)" )> /, "user.reinvoke()" );' file
Sample Input:
def get_user_creds(user):
# some lines of code
user.invoke()
user.process(user)
Sample Output:
def get_user_creds(user):
# some lines of code
user.reinvoke()
Raku is a programming language in the Perl family. Above the file is slurp
ed in (i.e. read into memory all at once), then a subst
itution is performed with the :global
parameter (adverb), meaning every two-line match in the file will be replaced.
The matcher / \h+ <( "user.invoke()" \n \h+ "user.process(user)" )> /
looks for the two literal strings (in double quotes), surrounded by the appropriate whitespace (\h
for horizontal whitespace, \n
for newline). Once matched, the <(
…)>
capture markers are used to delineate what is to be replaced. Here, the initial \h+
is not within the capture markers, and thus is retained in the output, adjacent to the newly inserted string (i.e. "respecting indentation").
Generally, escaping Regexes is a pain. However Raku simplifies the process by allowing literal strings (above, in double-quotes). If quotes are a problem, then backslashes work: simply backslash all non-[alnum or underscore] to have those characters understood literally. This reserves non-backslashed non-[alnum or underscore] characters (in the same category as ".
" dot) to take on special meaning in the future, even if no special meaning is conferred at the moment.
FYI, you can get very specific with captures/replacements. Below the strings "user." and "invoke()" are captured, and in the replacement "re" is interposed to make "reinvoke()":
~$ raku -e 'put S:g/ \h+ <( ("user.") ("invoke()") \n \h+ "user.process(user)" )> /$0re$1/ given slurp();' file
#OR
~$ raku -e 'put S:g[ \h+ <( ("user.") ("invoke()") \n \h+ "user.process(user)" )> ] = "$0re$1" given slurp();' file
https://docs.raku.org/language/regexes
https://raku.org
get_user_creds
. (b) what is the purpose of theg
global modifier in sed ?