sed and regex rule to substitute text

Viewed 38

I have the following text:

Before doing anything, curses must be initialized. This is done by calling the :func:`~curses.initscr` function, which will determine the terminal type, send any required setup codes to the terminal, and create various internal data structures. If successful, :func:`initscr` returns a window object representing the entire screen; this is usually called ``stdscr`` after the name of the corresponding C variable.

I want replace:

:func:`~curses.initscr`

with:

`initscr https://docs.python.org/3/library/curses.html#curses.initscr`_

and I tried the following sed rule:

's@ :func:`~curses\.\(.*\)`@ `\1 <https://docs.python.org/3/library/curses.html#curses.\1>`_ @g'

but the following is the result:

Before doing anything, curses must be initialized. This is done by calling the `initscr` function, which will determine the terminal type, send any required setup codes to the terminal, and create various internal data structures. If successful, :func:`initscr` returns a window object representing the entire screen; this is usually called ``stdscr` <https://docs.python.org/3/library/curses.html#curses.initscr` function, which will determine the terminal type, send any required setup codes to the terminal, and create various internal data structures. If successful, :func:`initscr` returns a window object representing the entire screen; this is usually called ``stdscr`>`_ after the name of the corresponding C variable. ::

1 Answers

Use

sed -E 's@ :func:`~curses\.([^`]+)`@ `\1 <https://docs.python.org/3/library/curses.html#curses.\1>`_ @g' file

See demo

EXPLANATION

NODE                     EXPLANATION
--------------------------------------------------------------------------------
   :func:`~curses          ' :func:`~curses'
--------------------------------------------------------------------------------
  \.                       '.'
--------------------------------------------------------------------------------
  (                        group and capture to \1:
--------------------------------------------------------------------------------
    [^`]+                    any character except: '`' (1 or more
                             times (matching the most amount
                             possible))
--------------------------------------------------------------------------------
  )                        end of \1
--------------------------------------------------------------------------------
  `                        '`'
Related