Find line in text file and insert txt above it

Anything VBScript-related, including Windows Script Host, WMI, ADSI, and more.
Forum rules
Do not post any licensing information in this forum.

Any code longer than three lines should be added as code using the 'Select Code' dropdown menu or attached as a file.
This topic is 14 years and 10 months old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked
User avatar
goldyfarbs
Posts: 239
Last visit: Thu Mar 07, 2013 8:15 am

Find line in text file and insert txt above it

Post by goldyfarbs »

Hey all..What is the best way to find a certain line in a text file and insert text above that line?For example, I want to find this line </Configuration>Now, if I always new this was the last light, I can just stuff it into an Array and delete the last line and then re-insert text I wanted, but I am not 100% sure that </Configuration> is always the last line.I mean, I can find and replace the text, but I am not sure if I can replace the text with three additional lines and how that will work.Any suggestions would be great.thx
User avatar
goldyfarbs
Posts: 239
Last visit: Thu Mar 07, 2013 8:15 am

Find line in text file and insert txt above it

Post by goldyfarbs »

You know how I love regular expressions... No particular pattern, just need to find the end of the configuration portion of this XML file and insert some text above it.
User avatar
goldyfarbs
Posts: 239
Last visit: Thu Mar 07, 2013 8:15 am

Find line in text file and insert txt above it

Post by goldyfarbs »

Joel,That is the original approach I was going too.. That is the exact format, but I didn't know if that was going to work..JV -Can you go into a little more detail
User avatar
goldyfarbs
Posts: 239
Last visit: Thu Mar 07, 2013 8:15 am

Find line in text file and insert txt above it

Post by goldyfarbs »

Yeah, I know very little, but I need to add a few lines of code to an XML configuration file and I would like to have it automated. Can JV's approach handle that?
User avatar
joel.delatorre
Posts: 83
Last visit: Tue Jan 17, 2017 9:26 am

Find line in text file and insert txt above it

Post by joel.delatorre »

Absolutely. Im sure he will post soon.
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

Find line in text file and insert txt above it

Post by jvierra »

Here is a VBScript version of teh above.

Same test file new tag name.

I also added logic to xpath the section but will only work for this file. XPath can be altered to work with different file schema.

If you run this code as it is it will show you why you must use XML. After running this the "" will not appear on a line by itself. It will be on the same line that has just been inserted. This is OK with XML and will happen often whenever a file is programatically edited. Editing with the DOM will prevent this from becoming an issue.


Code: Select all

	
Set xmlDoc = CreateObject("Msxml2.DOMDocument")
sFile = "c:test2.xml"
xmlDoc.load( sFile )
append_node xmlDoc, "//root/Configuration", "time_stamp", Time
xmlDoc.save sFile 
	
Function append_node( doc, xpath, name, text )
    Set nodes = doc.selectSingleNode(xpath )
    Set node = doc.createElement(name)
    Set textNode = doc.createTextNode(text)
    node.appendChild textNode 
    nodes.appendChild(node)
End Function
	
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

Find line in text file and insert txt above it

Post by jvierra »

What do you want to add to configuration. I m just adding a node with the time.


You nneed to post a ssample of your file and a sample of what you need to add to it.

An XML ffile is not a plain text file in that it has a very specific structure and set of rules. Line breaks, tabs and spaces do not exist in XML except as ways to make the file look pretty.

This:

is identical to this in XML:
<root>
<node>
node1
</node>
<node>
node2
</node>
</root>

The space is just to make it look pretty and can be deleted without causing an issue with the file.

The fso ReadLine method cannot deal with the XML format as it can change at any time.


jvierra2009-04-27 18:49:40
User avatar
goldyfarbs
Posts: 239
Last visit: Thu Mar 07, 2013 8:15 am

Find line in text file and insert txt above it

Post by goldyfarbs »

Ok, JV, SO, here it is.. It's the agentpanel config from patchlink

Code: Select all

<?xml version="1.0" encoding="UTF-8"?>
<!-- Project Agent XMAL-->
<configuration>
    <configSections>
        <section name="AgentConfiguration" type="Content.Common.Configuration.ConfigurationSection`1[[Content.Common.Configuration.ValuedConfigItem, Content.Common]], Content.Common"></section>
        <section name="ValueSource" type="Content.Common.Configuration.ConfigurationSection`1[[Content.Common.Configuration.ValueSourceConfigItem, Content.Common]], Content.Common"></section>
        <section name="LoggingSection" type="Content.Common.Configuration.ConfigurationSection`1[[Content.Common.Logging.LoggingConfigItem, Content.Common]], Content.Common"></section>
        <section name="Cryptography" type="Content.Common.Configuration.ConfigurationSection`1[[Content.Common.Cryptography.CryptographyConfigItem, Content.Common]], Content.Common"></section>
        <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
            <section name="NotificationManager.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"></section>
        </sectionGroup>
    </configSections>
    <AgentConfiguration>
        <confitems>
            <confitem name="AccountId" displayname="" sourcetype="Registry" source="HKEY_LOCAL_MACHINESOFTWAREPatchlink.comGravitixAgentConfigurationAccountId" encryption="None"></confitem>
            <confitem name="ServerName" displayname="" sourcetype="Registry" source="HKEY_LOCAL_MACHINESOFTWAREPatchlink.comGravitixAgentConfigurationServerName" encryption="None"></confitem>
            <confitem name="ServerPort" displayname="" sourcetype="Registry" sourcetypedefinition="DWord" source="HKEY_LOCAL_MACHINESOFTWAREPatchlink.comGravitixAgentConfigurationServerPort" encryption="None"></confitem>
            <confitem name="ServerSecure" displayname="" sourcetype="Registry" sourcetypedefinition="DWord" source="HKEY_LOCAL_MACHINESOFTWAREPatchlink.comGravitixAgentConfigurationServerSecure" encryption="None"></confitem>
            <confitem name="ServerUser" displayname="" sourcetype="Registry" source="HKEY_LOCAL_MACHINESOFTWAREPatchlink.comGravitixAgentConfigurationServerUser" encryption="None"></confitem>
            <confitem name="ServerPassword" displayname="" sourcetype="Registry" source="HKEY_LOCAL_MACHINESOFTWAREPatchlink.comGravitixAgentConfigurationServerPassword" encryption="None"></confitem>
            <confitem name="ProxySecure" displayname="" sourcetype="Registry" source="HKEY_LOCAL_MACHINESOFTWAREPatchlink.comGravitixAgentConfigurationProxySecure" encryption="None"></confitem>
            <confitem name="ProxyName" displayname="" sourcetype="Registry" source="HKEY_LOCAL_MACHINESOFTWAREPatchlink.comGravitixAgentConfigurationProxyName" encryption="None"></confitem>
            <confitem name="ProxyPort" displayname="" sourcetype="Registry" sourcetypedefinition="DWord" source="HKEY_LOCAL_MACHINESOFTWAREPatchlink.comGravitixAgentConfigurationProxyPort" encryption="None"></confitem>
            <confitem name="ProxyBypass" displayname="" sourcetype="Registry" source="HKEY_LOCAL_MACHINESOFTWAREPatchlink.comGravitixAgentConfigurationProxyBypass" encryption="None"></confitem>
            <confitem name="ProxyUser" displayname="" sourcetype="Registry" source="HKEY_LOCAL_MACHINESOFTWAREPatchlink.comGravitixAgentConfigurationProxyUser" encryption="None"></confitem>
            <confitem name="ProxyPassword" displayname="" sourcetype="Registry" source="HKEY_LOCAL_MACHINESOFTWAREPatchlink.comGravitixAgentConfigurationProxyPassword" encryption="Rsa"></confitem>
            <confitem name="LastPollTime" displayname="" sourcetype="Registry" source="HKEY_LOCAL_MACHINESOFTWAREPatchlink.comGravitixAgentLastPollTime" encryption="None"></confitem>
            <confitem name="NextPollTime" displayname="" sourcetype="Registry" source="HKEY_LOCAL_MACHINESOFTWAREPatchlink.comGravitixAgentNextPollTime" encryption="None"></confitem>
            <confitem name="PingPort" displayname="" sourcetype="Registry" source="HKEY_LOCAL_MACHINESOFTWAREPatchlink.comGravitixAgentPolicyPingPort" encryption="None"></confitem>
            <confitem name="TraceLevel" displayname="" sourcetype="Registry" source="HKEY_LOCAL_MACHINESOFTWAREPatchlink.comGravitixAgentPolicyTraceLevel" encryption="None"></confitem>
            <confitem name="AgentStatus" displayname="" sourcetypedefinition="DWord" sourcetype="Registry" source="HKEY_LOCAL_MACHINESOFTWAREPatchlink.comGravitixAgentStatus" encryption="None"></confitem>
            <confitem name="SleepMode" displayname="" sourcetype="Registry" sourcetypedefinition="DWord" source="HKEY_LOCAL_MACHINESOFTWAREPatchlink.comGravitixAgentTaskSleepMode" encryption="None"></confitem>
            <confitem name="AgentTaskState" displayname="" sourcetype="Registry" sourcetypedefinition="DWord" source="HKEY_LOCAL_MACHINESOFTWAREPatchlink.comGravitixAgentTaskSTATE" encryption="None"></
	confitem>
            <confitem name="AgentPath" displayname="" sourcetype="Registry" source="HKEY_LOCAL_MACHINESOFTWAREPatchlinkUpdate AgentPath" encryption="None"></confitem>
            <confitem name="AgentServiceName" displayname="Detection Service:" sourcetype="Registry" source="HKEY_LOCAL_MACHINESOFTWAREPatchlinkUpdate AgentServiceName" encryption="None"></confitem>
            <confitem name="LastDAUTime" sourcetypedefinition="Binary" displayname="The Last Vulnerability Detection was performed on:" sourcetype="Registry" source="HKEY_LOCAL_MACHINESOFTWAREPatchlink.comDiscovery AgentLastDAUTime" encryption="None"></confitem>
            <confitem name="DAUStatus" displayname="" sourcetype="Registry" source="HKEY_LOCAL_MACHINESOFTWAREPatchlink.comDiscovery AgentStatus" encryption="None"></confitem>
            <confitem name="PDDMPort" displayname="" sourcetype="Registry" sourcetypedefinition="DWord" source="HKEY_LOCAL_MACHINESOFTWAREPatchlink.comGravitixpddmPDDMPort" encryption="None"></confitem>
            <confitem name="NotificationPath" displayname="Notification Manager Version" sourcetype="Registry" source="HKEY_LOCAL_MACHINESOFTWAREPatchLinkUpdate AgentPath" encryption="None"></confitem>
            <confitem name="NotificationIconOn" defaultvalue="False" displayname="" sourcetype="Registry" source="HKEY_CURRENT_USERSoftwarePatchlink.comAgentNotification ManagerIconOn" encryption="None"></confitem>
            <confitem name="ProxyNameUI" displayname="" sourcetype="Registry" source="HKEY_LOCAL_MACHINESOFTWAREPatchlink.comGravitixAgentConfigurationProxyNameUI" encryption="None"></confitem>
            <confitem name="ClientAgentVersion" displayname="Detection Version:" sourcetype="Registry" source="HKEY_LOCAL_MACHINESOFTWAREPatchlinkUpdate AgentVersion" encryption="None"></confitem>
            <confitem name="ProductCode" displayname="" sourcetype="Registry" source="HKEY_LOCAL_MACHINESOFTWAREPatchlinkUpdate AgentProductCode" encryption="None"></confitem>
            <confitem name="FastPathRoutes" displayname="" sourcetype="Registry" source="HKEY_LOCAL_MACHINESOFTWAREPatchlink.comGravitixAgentPolicyFastPathRoutes" encryption="None"></confitem>
            <confitem name="FastPathInterval" displayname="" sourcetype="Registry" source="HKEY_LOCAL_MACHINESOFTWAREPatchlink.comGravitixAgentPolicyFastPathInterval" encryption="None"></confitem>
            <!--
            <confitem name="FastPathRoutes" displayname="" sourcetype="Registry" source="HKEY_LOCAL_MACHINESOFTWAREPatchlink.comGravitixAgentPolicyFastPathRoutesDEBUG" encryption="None"/>
            <confitem name="FastPathInterval" displayname="" sourcetype="Registry" source="HKEY_LOCAL_MACHINESOFTWAREPatchlink.comGravitixAgentPolicyFastPathIntervalDEBUG" encryption="None"/>
            -->
        </confitems>
    </AgentConfiguration>
    <Cryptography>
        <confitems>
            <confitem name="None" assembly="Content.Common.dll" type="Content.Common.Cryptography.Providers.NoProvider"></confitem>
            <confitem name="Rsa" assembly="Content.Common.dll" type="Content.Common.Cryptography.Providers.RsaProvider"></confitem>
            <confitem name="Blowfish" assembly="Content.Common.dll" type="Content.Common.Cryptography.Providers.BlowfishProvider"></confitem>
        </confitems>
    </Cryptography>
    <ValueSource>
        <confitems>
            <confitem name="Registry" assembly="Content.Common.dll" type="Content.Common.Configuration.RegistryConfigurationValue" caching="false"></confitem>
        </confitems>
    </ValueSource>
    <LoggingSection>
        <confitems>
            <confitem name="File" displayname="Agent Panel" assembly="Content.Common.dll" type="Content.Common.Logging.NullProvider" Path="C:Program Files (x86)Common FilesPatchLinkUpdate AgentLogsAgent.Panel.Error.log" Severity="Fatal"></confitem>
            <confitem name="Agent Deployment" assembly="Content.Common.dll" type="Content.Common.Logging.FileProvider" Path="PatchLink Update Agent.log" Severity="Debug"></confitem>
            <confitem name="Agent Inventory" assembly="Content.Common.dll" type="Content.Common.Logging.FileProvider" Path="Inventory Collector.log" Severity="Debug"></confitem>
            <confitem name="Agent Detection" assembly="Content.Common.dll" type="Content.Common.Logging.FileProvider" Path="PatchLink Detection Agent.log" Severity="Debug"></confitem>
            <confitem name="Debug" assembly="Content.Common.dll" type="Content.Common.Logging.DebugProvider" Path="null" Severity="Debug"></confitem>
        </confitems>
    </LoggingSection>
</configuration>
And I need to add the following section to the configuration part of the XML file,

Code: Select all

    <runtime>

	            <generatePublisherEvidence enabled="false"/>

	    </runtime>
This is because .Net goes and makes sure that the certificate is valid, but our servers don't have internet access, so the panel hangs and timesout for 5 minutes. We can trick it by editing the local host file, but I would rather edit this configuration file.

I am still trying to grasp what you have in place above,.. It's going to take some time for me to understand.
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

Find line in text file and insert txt above it

Post by jvierra »

Your root XPath is "Configuration" as I pointed out.

jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

Find line in text file and insert txt above it

Post by jvierra »

Code: Select all

Set xmlDoc = CreateObject("Msxml2.DOMDocument")
sFile = "c:testconfig.xml"
xmlDoc.preserveWhiteSpace = True
xmlDoc.load( sFile )

'<runtime></runtime>
append_node xmlDoc, "/configuration", "runtime", ""

'<generatePublisherEvidence enabled="false"/>
set node = append_node( xmlDoc, "/configuration/runtime","generatePublisherEvidence","")
Set attr = xmlDoc.createAttribute("enabled")
attr.value = "false"
node.SetAttributeNode(attr)
xmlDoc.save sFile 
	
Function append_node( doc, xpath, name, text )
    Set nodes = doc.selectSingleNode(xpath )
    Set node = doc.createElement(name)
    Set textNode = doc.createTextNode(text)
    node.appendChild textNode 
    nodes.appendChild(node)
    Set append_node = node
End Function
This topic is 14 years and 10 months old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked