There are many articles available of how you may set master page for the site (using SPWeb.MasterUrl and SPWeb.CustomMasterUrl), but as it turned out there is a lack of examples which show how you may programmatically change content of master page itself. Sometimes it may be needed, e.g. when there is a lot of site collections in web application and updating them manually would take too much time.
The following example shows how to modify content of master page via Sharepoint object model:
In this example we insert div element with custom content after first found SPSecurityTrimmedControl. In your scenarios you may need to insert another elements into another places in masterpage. In this case modify the logic as needed.
At first we read the content of the masterpage and store it to the string (lines 9-13). After that we determine place where new element should be inserted (lines 15-22). In next step we split content string into 2 sub strings: before and after insert position (lines 24-25). And finally insert new element to the string (lines 26-29). We could perform the same operations via regular expressions, but in this example we will keep it simple. After that we override existing file with the new content (lines 33-35) and check in, publish, approve it depending on masterpage gallery’s settings (lines 37-47).
In result we will have updated masterpage which content was changed programmatically. Hope that this information will help someone.