Linux – Command to insert/prefix characters in lines after searching for a phrase from a file

command-line-interfacelinuxunix

Similar to a question posted by me here earlier, am looking for a help in Linux command that performs/does the following that is subtle different from my original question:

Searches for a particular word/phrase case-insensitively in a given file, and then insert/prefix with the character -- (in this case, this is an SQL comment) in the immediate next 'n' lines including the line where the word/phrase was matched in the given file.

EXAMPLE:
If I try to search for the phrase "CREATE FUNCTION plpgsql_call_handler" case-insensitively and if it matches at line no.102644, then I expect to insert/prefix the character -- in line no.102644 and the immediate next 2 lines in the given file. In this case, I expect to insert/prefix line nos. 102644,102645,102646 with the character --.

Example file:

102644 CREATE FUNCTION plpgsql_call_handler() RETURNS language_handler
102645     AS '/usr/lib/pgsql/plpgsql.so', 'plpgsql_call_handler'
102646     LANGUAGE c;

I expect/want it to be changed into (in this case, it is an SQL comment):

102644 -- CREATE FUNCTION plpgsql_call_handler() RETURNS language_handler
102645 --    AS '/usr/lib/pgsql/plpgsql.so', 'plpgsql_call_handler'
102646 --    LANGUAGE c;

Best Answer

This is how you'd do it in-place with sed:

sed -r -i -e '/CREATE FUNCTION plpgsql_call_handler/I,+2 s/^/-- /'

(May require GNU sed.)

Replace 2 with the number of lines you want (or use any other sed address forms).

This is much simpler than that perl monstrosity. Also, perl could do it in place by using the -i as well:

perl -i -n -e horrible_perl_code /path/to/file

In both cases if you wish to keep a backup change -i to -i.bak.