Helps to replace a string in a txt file with a string from a csv file

Hi all

I worked on the script following since a few days now, determined to exhaust my own knowledge before asking for help... Unfortunately, it didn't take very long to exhaust my knowledge :-(

Basically, I need to replace a value in a single file (raw.txt) with the value of another file (userids.csv) when a variable is. Then I released the results of a third file.

To do this, I divided the "raw" file into variables using the ',' as the separator, the problem is that some variables are intentionally empty, where the fi $variable = "statements.

It is currently what I want to do but only when the userids.csv file contains a single line. It is obviously because of the foreach ($user in import)... What I need to figure out is how to loop through the file raw.txt, text replacement when a variable in the user ID file is the text in raw.txt... I hope that makes sense?

The user ID file is in the following format - user, service, Dept that can contain dozens of lines

I would appreciate any pointers :-)

See you soon

# Treatment
$importraw = get-content i:\raw.txt
$import = import-csv i:\userids.csv-en-tete UserAccount, functional, Dept

{foreach ($user in $import)
$useraccount = $user. UserAccount
$userfunction = $user. Functional
$userdept = $user. Dept
{foreach ($line in $importraw)
$first, $second, $third, $fourth, $fifth, $sixth, $seventh, $eighth, $ninth = $line - split(",")
$linesproc = $linesproc + 1
If ($sixth - eq ") {}
$temp6 = "6TEMP".
Write-Host "field Null detected - assigning temporary value:"$temp6 ".
$sixth = $temp6 # the assignment of a temporary value so that - statement to replace later works
}
If ($seventh - eq ") {}
$temp7 = "7TEMP".
Write-Host "field Null detected - assigning temporary value:"$temp7 ".
$seventh = $temp7 # the assignment of a temporary value so that - statement to replace later works
}
If ($fifth - eq $user.) UserAccount) {}
$line - $seventh, replace $user. Dept | Add content i:\Output.txt
}
else {}
$line - $seventh, replace "/ / customer. Add content i:\Output.txt
}
}

}

Try the attached version.

The problem, in my opinion, was in nested ForEach loops.

Instead I've implemented with a lookup table

Tags: VMware

Similar Questions

  • Search and replace the string from a result

    Hi all
    I want to search a "("or ")" of the chain and all want the string before replacing "(" with a blank space...


    for example
    If the result comes like this
    name
    12 #122 (on the opening balance)
    I want the result as

    name
    on the opening balance)

    means
    12 #122 is replaced by "" how


    thanking you
    Gaurav Sontakke

    Like this?

    WITH t AS
         (SELECT '10 #10 (moving standard to msp1004)' str
            FROM DUAL
          UNION ALL
          SELECT '13208 #0' str
            FROM DUAL
          UNION ALL
          SELECT '2002-02-22 #10' str
            FROM DUAL)
    SELECT SUBSTR (str, 1, INSTR (str, '#') - 1)
      FROM t
    
  • Through a set of query results, replacing one string by another.

    I want to write a function that replaces the occurrence of a string with another string different.  I need to be a CF fuction which can be called from another function CF.  I want to 'hand' this function (a string) SQL statement like this: (Please note, don't bother commenting "there are ways of writing this SQL try..., I made this simple example to get to the point where I need help.)  I have to use a 'sub_optimal' SQL syntax just to demonstrate the situation)

    Here's the string I want to pass to the function:

    SELECT

    [VERYLONGTABLENAME]. FIRST NAME,

    [VERYLONGTABLENAME]. LAST_NAME,

    [VERYLONGTABLENAME]. ADDRESS

    Of

    LONGTABLENAME [VERYLONGTABLENAME]

    Here are the contents of the ABRV table:

    TBL_NM, ABRV <! - header line - >

    VERYLONGTABLENAME, VLTN

    SOMEWHATLONGTALBENAME, SLTN

    MYTABLENAME, MTN

    ATABLENAME, ATN

    The function returns the string origin, but with the abbreviations in place names of the long table, example:

    SELECT

    VLTN. FIRST NAME,

    VLTN. LAST_NAME,

    VLTN. ADDRESS

    Of

    LONGTABLENAME VLTN

    Notice that only the table brackets and names that match a value in the table ABRV were replaced.  The LONGTABLENAME immediately following the FROM is left as is.

    Now, here's my attempt at amateur said written dum function: Please look at the comment lines for where I need help.

    < name cffunction output = "AbrvTblNms" = "false" access = "remote" returntype = "string" >
    < name cfargument = "txt" type = "string" required = "true" / >

    < cfset var qAbrvs = "" > <! - variable to hold the results of the query - >

    < cfset var output_str = "#txt #" > <!-I create a local variable so I can manipulate the data returned by the parameter TXT.  Is it necessary or can I use the parameter txt? ->


    < cfquery name = "qAbrvs" datasource = result "cfBAA_odbc" = "rsltAbrvs" >
    SELECT TBL_NM, ABRV FROM BAA_TBL_ABRV ORDER BY 1
    < / cfquery >

    <!-I'm assuming that at this point, the query is executed and records in the result-> set

    < cfloop index = list "idx_str" = "#qAbrvs #" > <! - is - right?  I do not. ->
    < cfset output_str = Replace (output_str, "#idx_str #",) <! - is - right?  I do not. ->

    < / cfloop > <!-who am I loop on?  What is the index? How to do the replacement of the chain? ->

    <!-the chunck, below is a partial of my Object Pascal from Delphi function that does the same thing

    I need to know how to write this part in CF9
    So what not of folklore
    Start
    s: = StringReplace (s, ' [' + FieldByName('TBL_NM').]) [AsString + ']', FieldByName ('ABRV'). AsString, [rfReplaceAll]);
    Following;
    end;
    ->

    < cfreturn output_txt >

    < / cffunction >

    I am mostly struggling with the syntax here.  I know what I want to do, I know how to get there in a different programming language, just not CF9.  Thanks for any help you can provide.

    RedOctober57 wrote:

    ...
    Thanks for any help you can provide.

    One:

     

    No you need not create a local variable that is a copy of the variable arguments that the scope of the arguments is already local to the function, but you are not referencing correctly the scope of the arguments, then you may be using a variable 'txt' in another scope.  So best practice would be to refer to "arguments.txt" where you must.

    Two:

    I know what I want to do, I know how to get there in a different programming language, just not CF9.

    Then a best start would be to descirbe what you want to happen and give a simple example in the other programming language.  Most of us is muti-lingual and can analyze code in any clear and clean syntax.

    Three:

         

    I think you want to be a loop on your recordset returned by the previous query, perhaps 'qAbrvs '.

    
    

    Four:

    Continuing on this assumption I suppose you want to replace each instance of the long chain with the short form string that record together.

    
    

    Five:

                  

    If this is true, then you loop through the set of records from tablenames and abbreviations that you want to replace the chain.

  • replace a string

    is it possible to replace a string? I mean, as in any programming language when you:

    String data = "abc";

    data = 'zxc ';

    I am trying to get the substrings of an initial string like '123.456.789.432.567' separated by the "." character, and when I get "123" at the first iteration, I do not know how to init the second iteration with "456.789.432.567" that I can't change the original string the process gets.

    Thank you

    A quick detour to the String\ vi.llb\Advanced might help a little to that.

    but the Crossrulz method has merit too.

    This period can be a delicate delimiter!

  • I need to replace a string in a text using BACK file.

    I need to replace a string in a text using BACK file. I can't do it manually because the file size is about 2 GB. Please suggest me a solution. Thanks in advance.

    Hi ArunVL,

    See the Microsoft article below and check if it helps.

    With the help of MS-DOS Edlin utility to edit text files

    http://support.Microsoft.com/kb/67706

  • Replace a string in the data of the element - OSB / Xquery

    I want to replace a string in a piece of XML data in OSB/XQuery. Pls help me... (by something in the XPATH expression or actions of the OSB)

    Scenario looks like - I want to remove "IND_" of the field type in the code xml.

    Input XML (OSB or XQuery) - stored in a variable say $cricInfo

    < CricInfo >
    < player >
    < drive >
    Sachin < name > < / name >
    * < Type > IND_BAT < / name >. *
    < / player >
    < drive >
    Barouk < name > < / name >
    < Type > IND_BOWL < / name >
    < / player >
    < drive >
    Dhoni < name > < / name >
    WK of < type > < / name >
    < / player >
    < / players >
    < / CricInfo >

    Output XML file

    < CricInfo >
    < player >
    < drive >
    Sachin < name > < / name >
    < * type > BAT < / name >. *
    < / player >
    < drive >
    Barouk < name > < / name >
    BOWL of < type > < / name >
    < / player >
    < drive >
    Dhoni < name > < / name >
    WK of < type > < / name >
    < / player >
    < / players >
    < / CricInfo >

    Best regards, Sesha

    may also adapt the 'identity Transform' to do some filtering on the item 'type ':

    Here the transformation of base:

    http://en.Wikipedia.org/wiki/Identity_transform#Using_XQuery

    at least you would avoid having to reproduce the overall structure of the document in your XQuery, which is always a Bad Thing (TM)...

    by the way, your XML file is not well formed, I fixed it here


    Sachin
    IND_BAT


    Barro
    IND_BOWL


    Dhoni
    WK


  • Find + replace text (string constant) does not work for screw Statechart module

    Hello

    I tried to do a mass find + replace a string in my code. Using Ctrl + F, LabVIEW 2012 correctly locates all the places where this string exists, including within the States transitions guards who have paths in this form:

    XYZ.lvsciagram.vi / Transition: Guard - diagram, Transition, data/part

    However, when I've specified that a replacement string, then click on 'Replace all', only 'normal' instances of screws replaced - instances in my diagrams had not changed.

    What is going on? Is there anything else I need to do?

    Thanks in advance.

    Looks like those that does not include how to find and replace is implemented in LabVIEW. You can try to replace just the statechart and see if that makes a difference, but it may simply not work.

  • Replace the string on a specific line

    Hi everyone thanks in advance for your time.

    I have almost finished a project, (a software to manage the booking of hotel rooms and a database of passengers).

    I made a function that writes a .txt file a cluster with some personal information string type fields, each field is separated by tabs, and each client separated by a line news.

    Example: name address phone etc.

    Robert xxxxxx yyyyyyy

    Patrick xxxxxx yyyyyyy

    Mila xxxxxx yyyyyyy

    Now I don't know how I can do to perform a search by name and to be able to change each field.

    Example:

    If I search for Patrick, I want to be able to change the address or phone number or any other field.

    I know how to search in a text file, until I reach the word, but I don't find a way to change the field and write once again the information in the same file in the same line of origin.

    Any contribution will be great! Thanks again.


  • Search and replace the string formatting

    Hello

    I try to do a search and replace the formatting of a string.

    In the example, I'm looking for the string 'SUCCESSFUL', but it must also begin by usbflash and some number + PASSED.

    I can't get the format to have a number between 1 and 99. The number of replacements should add up to 6 in this case. I tried with \d for any number, and I also tried [1-99].

    Make a right-click on the function search and replace the string.  There is an option to use regular Expressions.  Then give it a try.

    EDIT: You need to set the entry replace all to TRUE.

  • How to get the string (specified by row and column) of txt file with labview

    Hello world

    How to get the string (specified by row and column) of txt file with labview

    THX

    As far as I know, a text file has no column.  Be more specific.  Do you mean something like the 5th word on line 4, where the words are separated by a space, and lines are separated by a newline character?  You can read from the spreadsheet String function and set the delimiter to a space.  This will produce a 2D channels table.  Then use the table to index and give the line number and column number.

  • Need help to split a string

    Hello

    IM needing help to cut a string like this... A, B, C, ADV, RAHEEM, MOUSTAFA, Gauthier,... compare letters he's be numbers, but I get by using a string... Need to divide and put each number into a vector, in all positions...

    Can someone help me?  ..

    I'm using labview 6...

    Here is the screenshot of my logic...

    Hi faelnpaiva,

    all you need is 'String of spreadsheet in table' with a ',' as the delimiter.

  • How to replace the string "\" on json webservice?

    Hello

    I have problem with this json

    "{\"search_result\":[{\"name\":\"Mall Summarecon\",\"category\":\"BusinessEntity\",\"id\":\"1\"},{\"name\":\"Bamboo Dim Sum\",\"category\":\"BusinessEntity\",\"id\":\"2\"},{\"name\":\"Dimsum Ceker\",\"category\":\"Item\",\"id\":\"1\"}]}"
    

    I want to replace the string "\".

    the json are already working on my app via .cpp file

    I already add json.replace on my qml

    function simpleSearch(response){
            indicator.stop()
            model.clear()
            console.log("Response: "+response)
            var json = JSON.parse(response)
            json = json.replace('\\', ' ') // this is how the way i replace
            if (json == "[]")
                notFound.visible = true
    
            else
                model.append(json.search_result)
        }
    

    but still does not work

    is there a different way to replace it?

    Thank you

    Change your simpleSearchFinished as follows

    ....simpleSearchFinished()
    {
        QNetworkReply *reply = qobject_cast(sender());
        if (!reply->error()){
            QByteArray response = reply->readAll();
            response.replace("\\", "");
            if (response.startsWith("\"")){
                response.remove(0, 1);
            }
            if (response.endsWith("\"")){
                response.remove(response.length()-1, 1);
            }
            emit simpleSearchDone(response);
        }else{
            const int httpCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
            qDebug() << "ErrorCode" << httpCode << endl << \
                    "ErrorString" << reply->errorString();
            emit error(httpCode, reply->errorString());
        }
        reply->deleteLater();
        manager->deleteLater();
    }
    

    and QML

    function simpleSearch(response){
        indicator.stop()
        model.clear()
        var json = JSON.parse(response)
        if (json){ // is VALID/PARSED
            model.append(json.search_result)
        }
    }
    

    As I wrote, it is not a good workaround solution. The best is to send VALID JSON string directly from your server. But it works

  • Update the Blob column by replacing a string...

    Hello

    I have a table T1 with a (large binary BLOB) column, I need (you) to update the Blob string with replacement of a chain (in the Blob) with another string.

    The update failed: ORA-00933: not correctly completed SQL command

    CREATE table T1

    (

       ID                   NOMBRE (12)           PAS NULL,

    DELIVERY_CONTENT BLOB ,

    )

    Update   T1 The VALUE DELIVERY_CONTENT = LOB_UTL_PCKG . BLOBREPLACE ()DELIVERY_CONTENT 'old_string' 'new_string'( )

    WHERE ID in (...)

    ORA-00933: SQL not correctly completed command

    I use a function LOB_UTL_PCKG . BLOBREPLACE starting from this package

    CREATE OR REPLACE PACKAGE LOB_UTL_PCKG

    IS

    FUNCTION BLOBREPLACE ()p_blob BLOB p_what VARCHAR2 p_with_what VARCHAR2() RETURN BLOB

    FUNCTION BLOB2CLOB (p_blob BLOB) RETURN CLOB ;

    FUNCTION CLOB2BLOB (p_clob CLOB) RETURN BLOB ;

    END;

    /

    CREATE OR REPLACE PACKAGE BODY LOB_UTL_PCKG

    IS

    FUNCTION BLOBREPLACE ()p_blob BLOB p_what VARCHAR2 p_with_what VARCHAR2()RETURN BLOB 

    IS

    START

    RETURN CLOB2BLOB () REPLACE (BLOB2CLOB()p_blob), p_what p_with_what( ) );

    END BLOBREPLACE ;

    ------------------------------ BLOB2CLOB -------------------------

    FUNCTION BLOB2CLOB (p_blob in BLOB) RETURN CLOB

    IS

       v_clob     CLOB ;

    dest_offset INTEGER := 1 ;

    offset INTEGER := 1 ;

    lang_context INTEGER := DBMS_LOB. DEFAULT_LANG_CTX;

    warning INTEGER ;

    START

    DBMS_LOB. CREATETEMPORARY ( ) v_clob TRUE );

    DBMS_LOB. CONVERTTOCLOB( )

    v_clob ,

    p_blob ,

    DBMS_LOB. LOBMAXSIZE,

    dest_offset ,

    offset ,

    DBMS_LOB. DEFAULT_CSID,

    lang_context ,

    warning

    );

    RETURN v_clob ;

    END BLOB2CLOB ;

    ------------------------------ CLOB2BLOB -------------------------

    FUNCTION CLOB2BLOB (p_clob CLOB) RETURN BLOB

    ACE

       l_blob     BLOB ;

    l_dest_offset INTEGER := 1 ;

    l_source_offset INTEGER := 1 ;

    l_warning INTEGER ;

    lang_context INTEGER := DBMS_LOB. DEFAULT_LANG_CTX;

    START

    DBMS_LOB. CREATETEMPORARY()l_blob TRUE);

    DBMS_LOB. CONVERTTOBLOB( )

    l_blob ,

    p_clob ,

    DBMS_LOB. LOBMAXSIZE,

    l_dest_offset ,

    l_source_offset ,

    DBMS_LOB. DEFAULT_CSID,

    lang_context ,

    l_warning

    );

    RETURN l_blob ;

    END CLOB2BLOB ;

    END;

    /

    Concerning

    Djam

    It works well for me.

    Update T1 SET DELIVERY_CONTENT is LOB_UTL_PCKG. BLOBREPLACE (DELIVERY_CONTENT, 'old_string', 'new_string')

    Where IDSQL > 2 = 1;

    0 lines to date.

  • Replace the string with the formatted text

    Hello all - I'm back to my beloved project...

    I want to replace a string by a TextSelction (formatted text) and began with the famous feature of Jang FindAndReplaceString.
    Since my replacement comes from another document (sourceDoc), I edited to targetDoc activeDoc and introduced a second document (sourceDoc).
    The replacePara actually comes from a stone where he had been placed to avoid switch backwards between the documents in a book (where to find and replace) and source documents. In another function, I learned that information on the table requires the sourceDoc must remain open.

    • Of course, everything works fine until I want to insert the replacelement:
      erase line 26 is the string
    • Given that I do not insert a string, I skip lines 28 and 29 and try try line 30
    • On line 30 DocumentSource is Document object and replacePare object TextSelection. However, sourceDoc.replacePara is not set and
    • (as a result?) line 31 past the current contents of the Clipboard.

    Of course, there is a fog around me... and I need some sunshine.

    function FindAndReplacePara (targetDoc, findString, sourceDoc, replacePara, loopMax) {
      var tr = new TextRange();
      var restoreTR, frame = 0, loopCounter = 0, replacementCounter = 0;
      var findParams = new PropVals();
      var firstPgf = targetDoc.MainFlowInDoc.FirstTextFrameInFlow.FirstPgf;
      
      tr.beg.obj = tr.end.obj = firstPgf;             //  set up the starting text range as the very beginning
      tr.beg.offset = tr.end.offset = 0;              // of the flow. We'll move straight from beginning to end.
      trSaved = tr                                    // to come back after work
    
      findParams = AllocatePropVals(2);
      
      findParams[0].propIdent.num = Constants.FS_FindText;
      findParams[0].propVal.valType = Constants.FT_String;
      findParams[0].propVal.sval = findString;
      
      findParams[1].propIdent.num = Constants.FS_FindCustomizationFlags;
      findParams[1].propVal.valType = Constants.FT_Integer;
      findParams[1].propVal.ival = Constants.FF_FIND_CONSIDER_CASE;
    
      FA_errno = Constants.FE_Success;                // errno global, to be used to track the progress of the find and replace
      tr = targetDoc.Find(tr.beg, findParams);        // and do an initial find to get started.
      
      while(FA_errno === Constants.FE_Success && loopCounter++ < 2*loopMax) { //find and replace loop as long as we keep finding
        targetDoc.TextSelection = tr;                 // set up the text range to clear the original text
        targetDoc.Clear(0);                           // clear it
        
    //    targetDoc.AddText(tr.beg, replacePara);       // insert the new text at the original beginning of the text range
    //    tr.beg.offset += replacePara.length;          //  lets jimmy the text range in memory to place it directly after
        targetDoc.TextSelection = sourceDoc.replacePara;        // paste the whole replacement paragraph
        targetDoc.Paste (0);                          // <-- Current contents of clipboard is pasted !!!!
        if(FA_errno === Constants.FE_Success) {       // increment our return counter
          replacementCounter++;
        }
        FA_errno = Constants.FE_Success;              // ...  find the next instance. We'll reset FA_errno again just in case
        tr = targetDoc.Find(tr.beg, findParams);      // something screwy happened while we were replacing text.
      }
      targetDoc.ScrollToText(trSaved);                // we're done. Restore the document to it's original area of display
      return replacementCounter;
    } // --- end FindAndReplacePara
    

    Hi Klaus,

    Thanks for the explanation. I remember something like that GetTabRange of the way back. You have been quite patient and persistent with this project, indeed.

    So, as we are dealing with ranges of text here, I think that the only simple approach is to perform a copy and paste. There is no way to save a 'formatted' in a variable. The only super precise way would be to get a data structure of each text range TextItems in the sourceDoc, then meticulously recreate every element of the targetDoc. It would be very complicated, I think, so copy and paste seems the most logical. I wonder, though, if Miss me something, because I think that maybe you would have tried already so yes (?)

    In any case, I would do something like that, from line 30 of your original code sample (code untested here):

    App. ActiveDoc = sourceDoc;

    sourceDoc.TextSelection = replacePara;

    sourceDoc.Copy (0);

    App. ActiveDoc = targetDoc;

    targetDoc.Paste (0);

    ... etc.

    Does make sense, or am I barking the wrong tree, as they say?

    Russ

  • Replace the string value of table

    with cte as)

    Select val '123', 'abwec' double val1

    Union of all the

    Select "456" val, "mowerw" double val1

    Union of all the

    Select val '709', 'wkwere' double val1

    Union of all the

    Select val '078', 'awerwewerwreq' double val1

    )

    Select * from cte;

    -incoming string

    "asdasd123ewrwer@87w8eopiu456werwer@asdwer709@ewrwerewrwqqwezxder078 @..."

    need to replace like 'abwec' 123 and 456 as "mowerw" and 709 as wkwere and 078 as 'awerwewerwreq '.

    How to replace the string value of the string

    I'm going to the table which will have mapping information I need to see the incoming string and replace the appropriate value of the val to val1

    something like

    Of

    "asdasd123456werwer@asdwer709@ewrwerewrwqqwezxder078ewrwer@87w8eopiu @..."

    TO

    "asdasdabwecewrwer@87w8eopiumowerwwerwer@asdwerwkwere@ewrwerewrwqqwezxderawerwewerwreq@..."

    By using the TYPE clause.

    with cte as

    (

    Select val '123', 'abwec' double val1

    Union of all the

    Select "456" val, "mowerw" double val1

    Union of all the

    Select val '709', 'wkwere' double val1

    Union of all the

    Select val '078', 'awerwewerwreq' double val1

    ),

    input_tbl

    as

    (

    Select "asdasd123ewrwer@87w8eopiu456werwer@asdwer709@ewrwerewrwqqwezxder078 @..." input_str

    of the double

    )

    Select max (input_str) Dungeon (first order by desc NWR dense_rank) input_str

    de)

    Select rno, input_str

    de)

    Select rownum NWR

    val

    val1

    input_str

    count (*) over() cnt

    from cte

    Cross

    Join input_tbl

    )

    model

    dimension (NWR)

    measures (val, val1, cnt, CAST (input_str AS VARCHAR2 (4000)) input_str)

    (

    input_str [any] = replace (nvl (input_str [cv () - 1], input_str [cv ()]), val [cv ()], val1 [cv ()])

    )

    )

Maybe you are looking for

  • Game Center in MacOS Sierra...?

    Hi all. Trying to play WOT on my mac and can not find the game Center. Must have game center to connect on WOT Blitz. So, how do you get Game Center? Ive attached the picture of my version. Any help will be appreciated. Thank you!!

  • Hard drive MAC AIR died after 18 months

    Bought a Mac Air for my son 18 months ago. The hard drive needs to be replaced, and the estimate is $ 1000.00. May as well buy a new - very disappointing. Did this experiment with 3 computers HP laptop just out of warranty and decided to change to Ap

  • Firefox is completely black

    When I open the firefox browser, this morning, he did an automatic update. After the update the browser does not display anything, no menu, no Web, no Favorites pages. It is completely black.

  • Anyone who touches "House" on the cards does not?

    Whenever I hit "House" on the cards of apple, he asks me to update my info on my contact card. But I did over and over again without success. Does anyone else have this problem?

  • How can I get an another vista disk to reboot my laptop

    Hi all I had a system crash about a year because of a virus and a friend wiped my laptop and installed xp saying it was better than vista. However, I had nothing but bother with him for about 6 months now, it's just doesn't work the same and of cours