Search and replace data in excel using a text file

Hi Scripting Guy:
I was able to write a script based on all the examples in your blogs, but now I'm stuck:
I have a text file, which has Server Name, IP Address, Comments
ABCserver1, 1.1.1.1, remote web server
DEFserver2, 2.2.2.2, remote app server
XYZserver3, 3.3.3.3, remote api server
I have a excel file which has Server Name, IP Address, Protocol, Port. Server Name, and IP Addreess can repeat itself more than once in entire spreadsheet at any location: 
Server1, x.x.x.x, TCP, 80
Server2, x.x.x.x, TCP, 80
Server3, x.x.x.x, TCP, 80
My script search for the excel spreadsheet for a array that I have defined [Server1,Server2,Server3,...], once the first value matches in spreadsheet it replaces all values of Server1 with first value in text file i.e: ABCServer1 so my new excel sheet looks
this:
ABCserver1, x.x.x.x, TCP, 80
DEFserver2, x.x.x.x, TCP, 80
XYZserver3, x.x.x.x, TCP, 80
What I also want is, when I replaces the "Server1" value in spreadsheet, it will also replace the IP Address in next column. This is where I'm stuck I can replace the value of Server Name, but I can't replace the IP address for text file. Remember
"Server1" can be found at any place in spreadsheet but it will always have IP address column next to it.
So this is what script will do if runs correctly:
1) Read text file:
ABCserver1, 1.1.1.1, remote web server
DEFserver2, 2.2.2.2, remote app server
XYZserver3, 3.3.3.3, remote api server
2) Before script run on excel sheet
Server1, x.x.x.x, TCP, 80
Server2, x.x.x.x, TCP, 80
Server3, x.x.x.x, TCP, 80
3) After script run on excel sheet
ABCserver1, 1.1.1.1, TCP, 80
DEFserver2, 2.2.2.2, TCP, 80
XYZserver3, 3.3.3.3, TCP, 80
If you will see my script is able to replace "Server Name" in entire spreadsheet, but can't copy or replace the corespondent IP address in next column. 
script:
$text = "Server1","Server2","Server3"
$replace=$replace = get-content C:\script\test.txt | foreach{ ($_.split(","))[0]}
$File = "C:\script\test.xlsx"
$now = [datetime]::now.ToString("yyyy-MM-dd")
#$now = get-date -Format "MM-dd-yyyy_hh:mm:ss"
copy-Item C:\script\test.xlsx test_$now.xlsx
# Setup Excel, open $File and set the the first worksheet
$i=0
$Excel = New-Object -ComObject Excel.Application
$Excel.visible = $true
$Workbook = $Excel.workbooks.open($file)
$Worksheets = $Workbooks.worksheets
$Worksheet = $Workbook.Worksheets.Item(1)
$Range = $Worksheet.UsedRange
Foreach($SearchString in $text){
if ($Range.find("$SearchString")) {
    $Range.replace($SearchString,$replace[$i])
else {$i++}
$WorkBook.Save()
$WorkBook.Close()
[void]$excel.quit()
Really appreciate your help
Thanks

Hey, thanks for helping me out. I checked online and I had to call Cells this way:
$Workbook.Worksheets.Item(1).Cells.item($cell.Row,$cell.Column+1)=$test[$i].replace
one problem I'm having is if the $server value repeats itself in excel sheet again it doesn't replace all values for lets see server 1:
so thats how my excel sheet is:
server1
x
TCP
80
server2
x
TCP
80
server3
x
TCP
80
server1
x
TCP
80
when I run the script thats how results looks:
server1
x
TCP
80
REM88888SQL301A
10.1.1.2
TCP
80
REM88888SQL301B
10.1.1.3
TCP
80
REM88888SQL301
10.1.1.1
TCP
80
It skipped the line one on excel and changed value in line 4. As I mentioned above this can repeat $server can repeat itself anywhere in spreadsheet in multiple columns.
What can we do so it will replace all server name and IP address?
Thanks

Similar Messages

  • Search and replace, contents from excel file

    Hi
    I have the list in the excel file which needs to replace. The script should read the excel then replace to the opened InDesign documents.
    The excel(*.xls) file has two columns, first column has old nos. and the second column has the new numbers to replace.
    Ex:
    Column 1               Column 2
    (Search)               (Replace)
    4257/2          =>               1/2
    4257/3          =>               1/3
    4257/4          =>               1/4
    3257/2          =>               1/5
    3257/3          =>               1/6
    3257/4          =>               1/7
    4457/4          =>               2/2
    4457/5          =>               2/3
    4457/6          =>               2/4
    4457/7          =>               2/5
    Thanks in Advance,
    Thiru

    @csm_phil:
    this is a very radical method, because:
    1. you don't limit your changeGREP() to a specific table column (possibly the searched texts are found in other strings around the document and changed as well!)
    2. you are in trouble if a certain value you want to change exists more than one time (not likely, but who knows?) and you want to change it in diffrent values per instance. That will fail.
    If we deal with only ONE column of ONE table, to address issue 1 I would ask the user to select the column of the table and instead of:
    app.documents.item(0).changeGrep();
    I would use:
    app.selection[0].changeGrep();
    I don't hope issue 2 will apply in this case.
    @mr. pathi:
    However, in the case of only one column of one table to change AND if the new excel file contains ALL entries in the exact order (both all old and all new values), you could change the contents of the column by copying from excel to InDesign. No script necessary. The formatting of the old cells will be retained.
    You cannot do that by placing the new table to InDesign and copy/paste the new column to the old one, because the formatting of the copied column will be transferred as well (paste without formatting is not an option here).
    Uwe

  • Search and replace YYYYMMDD to DD-MM-YYYY (in file)

    I have a problem with date formatting. There is a mismatch between my banks .csv file and the standard of iBank...
    I would like to make an AppleScript (or Automator/AppleScript) app which search .csv file for strings "YYYYMMDD" and replaced it with "DD-MM-YYYY", but frankly I am not an AppleScript star There is a line of the .csv file below.
    "NL000BANK0000000000";"EUR";"20130101";"C";"100.00";"NL000BANK0000000000";"";"20 130102";"";"";"Accountholder";"Transactionnote";"";"";"";"";"";"";""
    Does anybody can help me with it?

    You could run the following in an Automator "Run Shell Scrpt" (or Applescript)
    awk '
            while( match($0,/\"[1-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]\"/) ) {
                date = substr($0,RSTART+1,8)
                year = substr(date,1,4)
                month = substr(date,5,2)
                day = substr(date,7,2)
                new = day "-" month "-" year
                if ( month+0 >= 1 && month+0 <= 12 &&
                     day+0   >= 1 && day+0   <= 31 &&
                     year+0  != 0                  ) {
                    sub(date,new,$0)
            print
    ' $1 >$HOME/new_$1
    You would change the "Pass input:" to "as arguments" which will populate $1 with the file you drag and drop onto the Automator app you create.
    The script will create a new file in your home folder with "new_" in front of the name from the file you dragged and dropped onto the automator app you create.

  • Search and replace, with pattern matching using a table

    I need to inspect a data stream and standardise a set of codes. I need to
    1. Match any patterns with a dash character and remove the dash and any following characters, eg BN-S -> BN, BN-SH -> BN, ARG-22 -> ARG, etc.
    2. Make a few specific word for word replacements, eg, PAEDSH -> PAED
    This is easy to hard code but can it be done using a table of regex substitutions? Can anyone give a pointer or link to some example code? The couple of regex replacement examples I've found use regex to locate but hard code substitutions.
    Thanks

    You could store all your patterns in a Map. Then iterate over the map inserting the patterns into a regex.

  • Search and Replace help. Please

    I have imported some text where in the original there is italic content but when bringing into IDCS4 that italic text shows up as _italic words_. That is as roman with _ characters surrounding it. Is there a way to search and replace. Needless to say the text between the _s varies.

    I would try a GREP find/change searching for (_)([^_]+)(_) and replace with $2 Set the change formatting to italics (preferably as a character style).  This translates to look for a _, then anything that is not a _, followed by another _, and replace with only the stuff in between. You can also use (_)(.+?)(_) which would match the shortest srting in between two _ characters in the same way (except it won't cross a paragraph break), but it will run a bit slower.
    Credit for this should go to Peter Kahrel and his excellent GREP primer....

  • [JS] About Search and replace

    Hello,
    Can anyone tell me how to Search and replace in a document using javascript.
    I want to replace ?? to 5.
    Thank you,
    --Avi

    doc.findTextPreferences.findWhat="??";
    doc.changeTextPreferences.changeTo="5";
    doc.changeText();

  • Case insensitive search and replace using ASP and Oracle database

    I am interested in providing a case insensitive search and replace query in a Active server page. At present data is collected from a html form which passes the text values to a ASP page. The ASP page runs a search (select query) to find if the data is already in the Oracle database, if it isn't the ASP page runs sql (INSERT) to insert the record, if not the page returns a form indicating that the record already exists. At present we can convert the case of new records using the VB UCase() function. But can't do a insensitive search with the existing records. *The Query must be able to utilize ASP variables.
    Any help would be much appreciated.
    David Cheryk
    null

    I can't check your script right now since I'm not on Mac. I recommend you to use FindChangeByList script for CS4 instead (it works with CS3): http://forums.adobe.com/servlet/JiveServlet/download/2080627-12695/FindChangeByListCS4.zip together with Martin Fisher's: http://www.kasyan.ho.com.ua/downloads/RecordFindChange_CS3_Kas.zip
    Use this script to record settings from Text and GREP tabs, then copy and paste them into FindChandgeList.txt file.
    Or, optionally you can use this script: http://www.kasyan.ho.com.ua/find_change_by_queries.html.
    Kasyan

  • How to search and replace in an xml file using java

    Hi all,
    I am new to java and Xml Programming.
    I have to search and replace a value Suresh with some other name in the below xml file.
    Any help of code in java it is of great help,and its very urgent.
    I am using java swings for generating two text boxes and a button but i am not able to search in the xml file thru the values that are entered into these text boxes.
    Thanks in advance.
    **XML File*
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <student>
    <stud_name>Suresh</stud_name>
    <stud_age>40</stud_age>
    </student>Also i am using SAX Parser in the java program
    any help of code or any tutorials for sax parisng is very urgent please help me to resolve this problem
    Edited by: Karthik84 on Aug 19, 2008 1:45 AM
    Edited by: Karthik84 on Aug 19, 2008 3:15 AM

    Using XPath to locate the elements you are after is very easy.
    Try something like this:
    import java.io.File;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import javax.xml.xpath.XPath;
    import javax.xml.xpath.XPathConstants;
    import javax.xml.xpath.XPathFactory;
    import org.w3c.dom.Document;
    import org.w3c.dom.NodeList;
    import org.xml.sax.InputSource;
    public class BasicXMLReplaceWithDOM4J {
         static String inputFile = "C:/student.xml";
         static String outputFile = "C:/studentRenamed.xml";
         public static void main(String[] args) throws Exception {
              // Read xml and build a DOM document
              Document doc = DocumentBuilderFactory.newInstance()
                        .newDocumentBuilder().parse(new InputSource(inputFile));
              // Use XPath to find all nodes where student is named 'Suresh'
              XPath xpath = XPathFactory.newInstance().newXPath();
              NodeList nodes = (NodeList)xpath
                   .evaluate("//stud_name[text()='Suresh']", doc, XPathConstants.NODESET);
              // Rename these nodes
              for (int idx = 0; idx < nodes.getLength(); idx++) {
                   nodes.item(idx).setTextContent("Suresh-Renamed");
              // Write the DOM document to the file
              Transformer xformer = TransformerFactory.newInstance().newTransformer();
              xformer.transform(new DOMSource(doc), new StreamResult(new File(outputFile)));
    }- Roy

  • GREP: date/time search and replace

    Hi everybody,
    I frequently import XML files to InDesign. The XML structure always contains the following information among others:
    start date
    start time
    end date
    end time
    For example, it looks like this:
    21.08.2013
    09:00
    25.08.2013
    18:00
    Now I need to re-arrange these fields in one row, just like this:
    21.08.2013, 09:00 - 25.08.2013, 18:00
    I already found out how to do this via GREP, but I need to go one step further:
    If "start date" and "end date" are the same (for example both are "21.08.2013"), I would like to skip the "end date" in the output. It should look like this:
    21.08.2013, 09:00 - 18:00
    Is there a way to do this via GREP?
    Thanks in advance!

    This will do it
    Trevor
    // By Trevor http://forums.adobe.com/thread/1261365?tstart=0
    app.doScript("formatDates ()", ScriptLanguage.javascript, undefined, UndoModes.ENTIRE_SCRIPT, "GREP: date/time search and replace");
    function formatDates ()
            app.findGrepPreferences = app.changeGrepPreferences = null;
            app.findGrepPreferences.findWhat = "\\d\\d\.\\d\\d\.\\d\\d\\d\\d\r\\d\\d:\\d\\d\r\\d\\d\.\\d\\d\.\\d\\d\\d\\d\r(?=\\d\\d:\\d\\d\r)";
            var doc = app.activeDocument,
                  dateFinds = doc.findGrep(),
                  l = dateFinds.length, dates;
            while (l--)
                    app.findGrepPreferences.findWhat = "(\\d\\d\.\\d\\d\.\\d\\d\\d\\d)";
                    dates = dateFinds[l].findGrep();
                    app.findGrepPreferences.findWhat = "(\\d\\d\.\\d\\d\.\\d\\d\\d\\d)\r(\\d\\d:\\d\\d)\r(\\d\\d\.\\d\\d\.\\d\\d\\d\\d)\r";
                    if (dates[0].contents == dates[1].contents) app.changeGrepPreferences.changeTo = "$1 $2 - ";
                    else app.changeGrepPreferences.changeTo = "$1 $2 - $3 ";
                    dateFinds[l].changeGrep();

  • GUI Based tool for search and replace using regular expression

    Hi,
    I have developed this small tool which can be used for search and replace in multiple files using reqular expressions.
    Features:
    1. Full regular expression
    2. GUI based with Highlighted results
    3. Preview for replace available
    4. Pure Java based.
    5. Its like unix sed and grep
    Please visit below site for download/more information :
    http://sourceforge.net/projects/regexsearchrepl/
    Thanks,
    Hitesh Viseria

    I agree with you, it cannot compete grep/sed/awk combination. I couldnt find anything even close to grep/sed for windows which will also have a preview and most important, free. That is what made me write this tool. I am trying to
    improve its performance and more features like history etc.
    Any suggestions on additional features are most welcome.

  • Regular expression to change Hour:Min:Sec time to Min:Sec using the Search and Replace tool

    Hi,
    I think the title says it all, but I've used a script to export a project from an NLE as a html file with a bunch of images and timecodes within table cells. For example, In=00:00:34 and Out=00:01:30 needs to be converted In=0:34 and Out=1:30. I think the Search and Replace is the most simple way of working that, but I've not experience with Regular Expressions (or much in that regard) so would really appreciate if someone could give me a hand writing the Regular Expression I need to achieve this.
    Thanks in advance,
    James

    Okay, so an example row is:
    <tr>
    <td align="left" valign="top"><p align="left"><img src="Snapshot At Event Start [00-01-22-19].jpg"><br>
    <strong>In: </strong>1:22<br>
    <br>
    </p></td>
    <td align="left" valign="top"><p align="left"><img src="Snapshot At Event End [00-01-24-25].jpg"><br>
    <strong>Out: </strong>1:24<br>
    </p></td>
    <td width="100%" align="left" valign="top"><p><strong>Cut to League Video</strong></p>
      <p><strong>Duration</strong>: 2<br>
      <strong></strong></p></td>
    </tr>
    I need to change it to:
    <tr>
    <td align="left" valign="top"><p align="left"><img src="Snapshot At Event Start [00-01-22-19].jpg"><br>
    <strong>In: </strong>1:22 seconds<br>
    <br>
    </p></td>
    <td align="left" valign="top"><p align="left"><img src="Snapshot At Event End [00-01-24-25].jpg"><br>
    <strong>Out: </strong>1:24 seconds<br>
    </p></td>
    <td width="100%" align="left" valign="top"><p><strong>Cut to League Video</strong></p>
      <p><strong>Duration:</strong> 2 seconds<br>
      <strong></strong></p></td>
    </tr>
    The script itself is something I found somewhere on the internet - it's for Sony Vegas.
    I've highlighted the changes with bold underlined italics.
    Thanks for you help, guys,
    James

  • Search and Replace using wild characters

    I have a bit of a problem on my hands while dealing jdom and xml. I am parseing an xml response from a service. The issue is that it contains an element with a colon. Nothing I can do about the service so I have to deal with it. I know I could use DOM and s on but I have chose to use jdom for a couple of reasons. What I am planning on doing is removing the colon in the element names with some sort of search and replace. The problem is that the there could be up to 500 element names with a numeric value. The element name looks like the following ns1:Point, ns2:Point, ns3:Point, and so on. JDom will not handle this so I would like it the element name to look ns1Point, ns2Point, etc. I have the xml returned from the service in a string. Is there any way I can do a search and replace given the above information. Thanks in advance

    Silverfoot wrote:
    I realize that it seperates the name space. The namespace for the element is different than ns1. Maybe I am missing something though
    Using JDOM, I navigate my way through the xml using getChild(elementname, namespace). When i get to ns1:Point, i use the same namespace as previous elements. Are you suggesting that ns1 is another namespace. In that case I would use a second name space to the Point element.I think you're missing a whole lot, actually. You don't seem to know much about namespaces. For a start you're apparently making the beginner error of assuming that the namespace prefix declares the namespace. And this idea:
    What I am planning on doing is removing the colon in the element names with some sort of search and replace.is just wrong. I would suggest you go off and find a tutorial (or a chapter in your XML book) about namespaces.

  • Catalog manger "search and replace " using xml script

    Hi ,
    we have renamed 6 rpd columns names in rpd & alias is not removed yet .In catalog manager i can search and replace using string .But it takes lot time as they are stored in different reports , which are existing . I am trying to use xml script for replacing them.I got sample script from help file for single column . can anyone help for doing that for multiple strings.I will provide with my inputs .
    my inputs:
    <?xml version="1.0" encoding="utf-8"?>
    <actions>
    <action command="textReplace" oldValue="column 1 " newValue="column one" ignoreCase="true"/>
    <action command="textReplace" oldValue="column 2" newValue="column two" ignoreCase="true"/>
    <action command="textReplace" oldValue="column 3" newValue="column three" ignoreCase="true"/>
    </actions>
    please correct me .

    Given xml content looks okay but just in case check this oldValue="column 1 ", there is additional space at the end.
    I would suggest to extract Analysis report (.csv) using Catalog Manager and find out the list of reports based on those columns.
    This would help you learn with list of reports based on report owners, and then go for the fixing those reports.
    If you go by xml replace you never know the affected reports and you may not confirm until report owners come back to you with issues.
    This might take little bit time but your changes based on proper doc.
    Let me know updates, if helps mark
    Edited by: Srini VEERAVALLI on Feb 19, 2013 3:21 PM

  • Using a variable in a Powershell search and replace string

    Hi
    a couple of days ago I posted a question about doing a search and replace with wildcards
    Search and repalce with Widcards
    I got a swift and very helpful answer but now I need to build on it.
    In a text file I wanted to replace all the text between two defined words.  the script I got was this
    $text = 'Some Server this bit of text varies Language stuff'
    $text -replace '(.*Server) .+? (Language.*)','$1 it will always say this $2'
    It works great but now I want to replace "it will always say this" with a variable and I can't figure out the correct grammar to make this happen.
    Can anyone help??
    Thanks
    Alex

    Here's one way:
    $replace = 'it will aways say this'if ( $text -match '(.*Server) .+? (Language.*)' )
    { "{0} $Replace {1}" -f $matches[1,2] }
    else { $text }
    [string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " "

  • How to get numeric result from 'search and replace' string function

    hii
    i am using search and replace function to get output.my output is of form ' *X0123.3 ' .here i am replacing the term *X01 with space because i need only 23.3 as a result.but i am unable to get that out in the output indicator.i used lot of functions like string to number and so on but i am getting output as zero .can you please suggest me wt to do.i am attaching a copy of my file.
    Attachments:
    Untitled 1.vi ‏25 KB

    Your problem is the fact that you are converting it to an integer, thus loosing the fractional part. You need to use "Fract/Exp String To Number" instead and create a DBL so yor data is 23.3 instead of 23.
    You also don't need to manipulate the string if the initial part is of constant lenght. Just use the offset input as in the figure below.
    Message Edited by altenbach on 07-31-2006 07:02 AM
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    ToDBL.png ‏2 KB

Maybe you are looking for

  • Connecting HP Laserjet 6l

    Hello again, I recently found a working HP laserjet 6l curbside recently and I am wondering what's the best way to connect it to my Mac G4. I read somewheres off of google search about it might work with some of the built in drivers in OSX but as far

  • Media Encoder CS4 won't update - Mac

    I have CS4 and Adobe media encoder 4.1.0 will not update, I have downloaded it via software update and then it installs and after a check of software update it asks me to update exactly what I just updated. Does anyone know how I can sort this issue

  • Problem with the discount field in PO form.

    Hi All I have a major problem in the PO form when ever I capture an invoice and then i insert the amount like R 100 000 then I try and add it with out maybe be a date in , the system will give me an error about date which is fine then I put in my dat

  • Built application doesn't 'see' user.lib?

    New AppBuilder user here. I seem to be having a problem building a standalone application that has a few custom VIs in it.  Debugging showed that it apparently refuses to recognize the custom VIs in my user.lib folder.  I tried disabling them in my s

  • Accessing a java class method from the jsp page.

    Hi im a beginner with jsp and im trying to find a way to access a method of my java class file in jsp page. After searching through the forums i tried to use the usebean tag. Im using apache to host the jsp file.Below is an excerpt of my code and the