Thursday, July 27, 2017

Perl Insert Contents of One File Into Another at Line Matching Regex

Nice to have something I think is better than stackexchange - how often does that happen :) ?

To insert after a line matching the regex

perl -n -i -e 'print; print `cat FILE_TO_INSERT` if m#REGEX_TO_MATCH#; ' FILE_TO_MODIFY

To insert before :

perl -n -i -e 'print `cat FILE_TO_INSERT` if m#REGEX_TO_MATCH#; print;' FILE_TO_MODIFY

If you want the insertion to happen at the first match ONLY :

perl -n -i -e 'print `cat FILE_TO_INSERT` if m?REGEX_TO_MATCH?; print;' FILE_TO_MODIFY

A very valid question is, what do you do if your match pattern has the question-mark character? :)

https://unix.stackexchange.com/questions/32908/how-to-insert-the-content-of-a-file-into-another-file-before-a-pattern-marker

No comments: