Trim text in CSV to first 50 characters

Hi,
Hoping to get a little help with this.
I have a CSV file which is generated by another script. But i need to make sure that none of the values in the CSV file are greater than 50 characters long. Can someone help me compile a powershell script that reads the contents of the CSV and deletes any
excess characters in a  value in the CSV which is greater then 50 characters long.
Thanks
Regards,
Denis Cooper
MCITP EA - MCT
Help keep the forums tidy, if this has helped please mark it as an answer
Blog: http://www.windows-support.co.uk 
Twitter:   LinkedIn:

Sorry - I forgot you had the "if" in there.
The one I posted shows you how to generalize a solution using PowerShell components.  It will work on any CSV file without modification.
You don't need parens and it would be easier to understand if you formatted it correctly.
import-csv apps.csv |
if($_.DisplayName.length -gt 50){
Write-Host 'Shrinkin' -fore green
$_.DisplayName = $_.DisplayName.Substring(0,49)
$_
} |
Export-Csv newfile.csv -NoType
OR
$imp=import-csv apps.csv
$imp |
if($_.DisplayName.length -gt 50){
Write-Host 'Shrinkin' -fore green
$_.DisplayName = $_.DisplayName.Substring(0,49)
$imp | Export-Csv newfile.csv -NoType
Mixing both methods may make the script harder to understand and may make it prone to edit/update errors.
¯\_(ツ)_/¯

Similar Messages

  • ?xml version="1.0"? tag not appearing as first characters in document

    Hi,
    JSP below successfully creates a XML document but it includes a blank line before the <?xml version="1.0"?> tag.
    This causes my PL/SQL to return a "ORA-20100: Error occurred while parsing: PI names starting with 'xml' are
    reserved." error when using the XMLPARSER package.
    I am outputting the XML to IE5.0 but even if I do a SYSTEM out I get the same blank line before the initial tag.
    There are posts on here that confirm the PI error is caused by the tag not being the first characters in the document, but no solution/fix is provided.
    Any ideas much appreciated.
    JSP Code
    <%@ page import="java.sql.*, oracle.jbo.*, oracle.jdeveloper.cm.*, oracle.jdbc.*,oracle.xml.sql.query.*" %>
    <%String driver="oracle.jdbc.driver.OracleDriver";
    Driver d = new oracle.jdbc.driver.OracleDriver();
    String dbURL="jdbc:oracle:thin:@localhost:1521:mydb";
    String login="i2k";
    String password="fred";
    Connection cn = null;
    cn = DriverManager.getConnection(dbURL,login,password);
    // SQL Statement from URL Parameters
    String sql = request.getParameter("sql");
    if(sql == null){
    sql = "select * from vfi_trans";
    // Create SQL-to-XML Handler
    OracleXMLQuery q = new OracleXMLQuery(cn, sql);
    // Use <TransactionList> as document element for Rowset
    q.setRowsetTag("TransactionList");
    // Use <Transaction> for each row in the result
    q.setRowTag("Transaction");
    // set encoding
    q.setEncoding("iso-8859-1");
    // ensure lower case element names
    q.useLowerCaseTagNames();
    // Generate XML results and write to output
    String xmldoc = q.getXMLString();
    out.println(xmldoc.trim());
    //System.out.println(xmldoc.indexOf("\n"));
    cn.close();%>
    PL/SQL
    PROCEDURE XML_HANDLER2 IS
    -- MODIFICATION HISTORY
    -- Person Date Comments
    vfiURL VARCHAR2(100);
    parser xmlparser.Parser;
    vfiXML xmldom.DOMDocument;
    transactions xmldom.DOMNodeList;
    transactions_found NUMBER;
    curNode xmldom.DOMNode;
    textChild xmldom.DOMNode;
    v_itrans_site vfi_trans.itrans_site%TYPE;
    BEGIN
    dbms_output.put_line('Integrator 2000 Transactions');
    -- This is the URL to browse for an XML-based vfi feed of stories on XML
    vfiURL := 'http://10.1.1.111:7070/i2k25_html/ShowQuery.jsp?sql=select%20*%20from%20vfi_trans';
    -- Set the machine to use as the HTTP proxy server for URL requests
    http_util.setProxy('MYPROXY');
    -- Parse the live XML vfi feed from Moreover.com by URL
    parser := xmlparser.newParser;
    vfiXML := xml.parseURL( vfiURL );
    xmlparser.freeParser(parser);
    -- Search for all <headline_text> elements in the document we recieve
    transactions := xpath.selectNodes(vfiXML,'/TransactionList/ITRANS_ID');
    -- Loop over the "hits" and print out the text of the title
    FOR j IN 1..xmldom.getLength(transactions) LOOP
    -- Get the current <headline_text> node (Note the list is zero-based!)
    curNode := xmldom.item(transactions,j-1);
    -- The text of the title is the first child (text) node of
    -- the <headline_text> element in the list of "hits"
    -- textChild := xmldom.getFirstChild(curNode);
    v_itrans_site := xpath.valueof(curNode, '.');
    dbms_output.put_line('('| |LPAD(j,2)| |') '| | v_itrans_site);
    END LOOP;
    -- Free the XML document full of vfi stories since we're done with it.
    xml.freeDocument(vfiXML);
    EXCEPTION
    WHEN OTHERS THEN
    RAISE;
    END; -- Procedure
    null

    Charles,
    I believe that the blank line is caused by the JSP engine when it strips out the '<%@ page import...>' (replace bracket with brace) statement. God (or at least Larry E) forgive me for posting a link at IBM, but this article speaks to your issue:
    http://www-106.ibm.com/developerworks/library/j-dynxml.html?dwzone=ibm
    Maybe you need to put the <?xml?> tag in the jsp itself and strip it out of your xmldoc before outputting it.
    Good luck.

  • How to pass line text into string of 72 characters

    Hi,
    I need to to pass  material text lines to a file for processing into different SAP system.
    Currently i am having multiple text lines stored in an internal table. I am looping that table and checking the string length of a first line.If it is less than 72 characters then i need to add spaces at the end of the text and make it 72 and pass it to workarea-field.
    However, while passing the next line text it is overwriting the spaces of first line and that is making the text meaning difficult to understand when passed to the other SAP system.
    Let me know how to approach.
    Thanks,
    Ankur

    Hi,
    This will not work as it splits the text as per the position.
    However what i would need is if i am entering text like this.
    Material ABCD --> Line 1
    This is finished product 9-series material used for high-value equipments. ---> Line 2
    Currently,  when transferring this data over the file it goes to the other system as
    Material ABCDthis is finished product---> upto 72 characters
    9 series material used for high-value ---> upto 72 characters
    equipments.
    So if there is less than 72 characters in the first line it takes 2nd line text. However it is ok if the text has more than 72 characters as it goes into the next line and still makes the meaning intact.

  • Data aggregation by the 2 first characters of a characteristic

    Hi,
    in a query, i'd like to extract the two first characters of a characteristic and aggregate a key figure.
    For example, i have the characteristic material number and the quantity.
    Mat numb      0Qty
    01AAAA         1
    01BBBB         1
    01CCCC         2
    02AAAA         2
    02DDDD         3
    AATTTTT        3
    Here is the result i want :
    Mat numb      0Qty
    01                 4
    02                 5
    AA                3
    i can't use the selection condition because i don't know what is the value of the 2 first Characters. i don't want to modify the infocube by adding a new characteristic?
    Is there any regular expression in the selection condition i can use ( for ex : for characteristic Material Number, select the first character between 0 and A and the second between 0-A and *) ?
    Do i have to do it by using a user exit ?
    Thanks for your help.

    When I did that it juts brought over the text from the table of contence.  I thought maybe that was needed. So I deleted what was their before and replaced it with what popped in.  I did the same for the section pages.  Just to see what happened.  It brought in the section numbers and it did pretty much the same. I'm fine with relabeling my pages to match. The table of contents.    I still would like that first chapter page in the table of contents to actually link to the page if possible.  It still not linking right. 

  • Dynamic text don't show some characters

    hi guys,
    i'm with a problem.. i have a dynamic text in my flash and
    it's reading vars from a txt file, but it does not read some
    portuguese character as ç Ç or accents such as ã
    â Ã Â...
    i tried to embendding theses characters on my dynamic text,
    choosing embed>all and it doesn't work...i already tried to
    write them on the text box and embed>auto fill but it still
    work!!
    am i missing something?
    help me,please!

    Well the characters you mentioned should be in most regular
    fonts as well. They are hardly exotic enough to warrant a complete
    unicode font. I'm guessing the key something else. Of course it
    depends upon what font you are using. But most fonts that come with
    a computer and regular software should have those characters.
    You mention you are reading the vars from a txt file. Try
    this in the testing environment. Test publish your FLA and once the
    text file has been read go up to the debug menu and List Variables.
    Some place there should be the contents of the text file. Do the
    characters show up correctly there?
    If they don't, then the problem is that Flash isn't reading
    the text file correctly and no font will be able to fix that. Be
    sure that you are saving your text file as UTF-8. Flash doesn't
    play so well with other formats and beyond the basic ASCII range in
    text files.
    If they do show up correctly in the List Variables. Then you
    know the problem is with your fonts. As I said most fonts should
    have those characters so post back if you need more help.

  • SQL Plus Text is wrapping after 80 characters.

    The following is the sql I am using to spool the data into a file. However, I am confused with the output. The text is wrapping after 80 characters and it is adding blank lines after each column in the select. Am I missing some thing here. I appreciate your help.
    set echo off
    set feedback off
    set termout off
    set heading off
    set verify off
    set pages 0
    set long 20000
    set linesize
    clear columns
    spool /opt/consort/hari/hl7_msgs_533.txt
    select rtrim(msh_seg) ||
    rtrim(pid_seg) ||
    rtrim(pv1_seg) ||
    rtrim(orc_seg) ||
    rtrim(zri_seg) ||
    rtrim(obr_seg),
    segment_value
    from hl7_msgs where message_id = 1;
    spool off;
    Here is the output.
    PID|1|007985541|007985541||MOORE,WILLIE,||11-JAN-90|M|||3000 DOLFIELD AVE^^TAL
    TIBORE^CP^21215||(510) 766-7000||||BAP||100-10-1000||||||||||||^M
    PV1|1 |I|ICU^S412^A||||JAKOBOVITS,JULIAN,MD,MD|,,,||MED|||||||JAKOBOVITS,JULIA
    N,MD,MD|I ||||||||||||||||||0 ||||||||09-NOV-97|18-NOV-97||||||||^M
    ZRI|1 |LIBRARY GROUP|FILE RM|FILE RM|10-NOV-97||S412|||RAD|^M
    OBX|1 |TX|ULT00004^VENOUNI/US^VENOUS IMAGING WITH DOPPLER|||~~RIGHT LOWER EXTR
    EMITY VENOUS DOPPLER SONO, 11-10-97, -8965~CLINICAL INDICATION: cellulitis, r/o
    DVT~~The right common femoral vein, superficial femoral vein and popliteal veins
    were scanned using color flow, duplex and B-mode scanning. The veins were comp
    ressible and showed spontaneous flow which augments normally with compression of
    the calf.~~IMPRESSION:~~No evidence of deep venous thrombosis in the right femo
    ral and right popliteal veins. ~~ ||||||F ||||784|CAMP,LIBA,DD,CD||^M
    OBR||9711102125132|35|ULT00004^VENOUNI/US^VENOUS IMAGING WITH DOPPLER|||10-NOV-9
    7|10-NOV-97||||||||JAKOBOVITS,JULIAN,MD,MD||||||12-NOV-97|||||||||DOPPLER FLOW S
    TUDIES OF R LEG R\O DVT|CAPITAL,SUSAN,CD,|||FORD,VONDA,SKETERS,|||||||||^M
    ~******************************************
    ~
    ~

    It still wraps up the output.
    You may have embedded carriage returns in your columns.
    Let me explain you with an example.
    SQL> create table mytable(col1 varchar2(80));
    SQL> insert into mytable
      2  select lpad('ab',80,'cd') from dual;
    1 row created.
    SQL> select lpad('ab',50,'cd')||chr(10)||lpad('ab',29,'cd') from dual
      2 
    SQL> insert into mytable
      2   select lpad('ab',50,'cd')||chr(10)||lpad('ab',29,'cd') from dual;
    1 row created.
    SQL> select * from mytable;
    COL1
    cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdab
    cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdab
    cdcdcdcdcdcdcdcdcdcdcdcdcdcab

  • Restrict on the first characters of a characteric value

    Hi Experts,
    I would like to restrict some characterics on the three or four first characters of the value. For example, imagine the value 'ABCD-1234'; i would like to filter only values which begin with ABC.
    Is that possible unless doing a routine in the customer exit? If yes, how?
    Thanks in advance.
    Luc

    I need to do this in the query def. The list of the values can change but the format will be always the same (beginning with ABC); that's why I can't make a range of values because I risk not to take into account all the good values.
    This an example of values:
    SEEC3-2004-321
    SEEC3-2004-346
    SEA31-2004-584
    SEA31-2004-724
    SCY54-2004-828
    SCY54-2004-869
    SEA31-2004-888
    SCY54-2004-911
    SEE54-2004-928
    SEE31-2004-952
    SEE54-2004-1034
    I just want to restrict on values which begin with SEEC and SCY. Do you see a possible solution?*
    Thank you all

  • Tried to trim a video clip for first time iOS 6 trimming in progress last 10 hours. Not responding cant access photos. Help

    Tried to trim a video clip for first time iOS 6 trimming in progress last 10 hours. Not responding cant access photos. Help

    Reset your device by pressing the home button along with the sleep/wake button until you see the apple, then let go.

  • How to get Mountain Lion Spotlight to find text in CSV files?

    Does anyone know how to get Mountain Lion Spotlight to find text in CSV Files? Spotlight worked flawlessly with Snow Leopard on my last MAC but with Mountain Lion it doesn't recognize CSV Files. I have researched this extensively and haven't found any solution but I really believe there must be many others who have the same problem. I even contacted Apple's Genius Bar which was of no help whatsoever, they couldn't even tell me why Spotlight wasn't finding text in CSV Files, i.e., function dropped by Apple, bug, etc.
    Thru research I found that if the CSV Files are converted to 'Plain Text Files' Spotlight will find text inside of the files but I typically save my spreadsheets as CSV Files and don't want to have to convert them to Plain Text Files just so Spotlight will search them.
    I appreciate any help you can give.
    Joel

    I should have mentioned earlier that I do NOT have any exclusions set under the Spotlight Privacy tab, however, I did move one of the folders that contains CSV Files in then back out of the Privacy tab to try and get Spotlight to index the folder, but to no avail.
    I have a second Admin account and tried to find text in CSV Files while in that account, again to no avail. I also tried upgrading to Mountain Lion 10.8.4 to see if it might fix the problem, but no soap.
    Below is a screenshot of the Systems Preferences/Library/Spotlight/RichText.mdimporter/ file and I don't even see where Spotlight is setup to find CSV Files on my computer, very confusing but thanks again for your input.

  • I am only recieving part 2/2 of my text mesages, never the first part?

    I am only recieving part 2/2 of my text mesages, never the first part?  Does anyone else have this issue or a solution

    Try contacting your service provider about this issue.

  • Limit the amount of characters of a text field based on first digit

    Hello and thanks in advance for your help!
    I would like to limit the amount of characters of the text field based on the first digit of the number (the text field is only limited to a number format...no decimals, no commas).
    For example, if the number begins with a 3, I would like to limit the text field to allow only ten characters. I have three scenarios but if I could get started with some code and what is the best place to add it (keystroke or validation?) I can take it from there. Thanks again for your help!!

    I've written this code for you that does that. Use it as the field's custom Keystroke code:
    // Validate that only digits are entered
    if (event.change) {
        event.rc = /^\d+$/.test(event.change);
    // Validate string length if it starts with 3
    if (/^3/.test(AFMergeChange(event))) {
        event.rc = AFMergeChange(event).length <= 10;
        if (!event.rc) app.alert("If the number starts with \"3\" it may not be longer than 10 digits.",1); // optional error message
    You can duplicate the second part of it for additional conditions, but keep in mind that this code won't even let you remove the first character in the field if the result is an invalid one.
    For example, if you enter "234567890123456" then you can't remove the "2" at the start because that would result in an invalid number. You can remove any of the other digits, though, and when it's 10 digits or less then you could remove the starting "2" as well.

  • Upload text files with non-english characters

    I use an Apex page to upload text files. Then i retrieve the contents of files from wwv_flow_files.blob_content and convert them to varchar2 with utl_raw.cast_to_varchar2, but characters like ò, à, ù become garbage.
    What could be the problem? Are characters lost when files are stored in wwv_flow_files or when i do the conversion?
    Some other info:
    * I see wwv_flow_files.DAD_CHARSET is set to "ascii", wwv_flow_files.FILE_CHARSET is null.
    * Trying utl_raw.cast_to_varchar2( utl_raw.cast_to_raw('àòèù') ) returns 'àòèù' correctly;
    * NLS_CHARACTERSET parameter is AL32UTF8 (not just english ASCII)

    Hi
    Have a look at csv upload -- suggestion needed with non-English character in csv file it might help you.
    Thanks,
    Manish

  • Reading a text file with foreign language characters

    I'm trying to convert foreign language characters to English looking characters.  I have code that works, but only if I hard code the string with foreign language characters and pass it to the function. I cannot figure out how to get my program to read
    in the foreign characters from my file, they come in as garbage. 
    Since the function works when I pass a hard coded string to it, I'm pretty sure the problem is the way I have the Streamreader set up, it's just not reading the characters correctly...
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim FileRdr As StreamReader = New StreamReader "m:\test\charReplace.txt", System.Text.Encoding.UTF7)
    Dim ReplaceWrtr As StreamWriter ReplaceWrtr = System.IO.File.CreateText("M:\test\CharReplaceOut.txt")
    Do While FileRdr.Peek() >= 0
    Dim currentRec As String = FileRdr.ReadLine
    removeAccent(currentRec)
    ReplaceWrtr.WriteLine(currentRec)
    Loop
    ReplaceWrtr.Close()
    End Sub
    'Replace foreign language characters with English characters
    Function removeAccent(ByVal myString As String)
    Dim A As String = "--"
    Dim B As String = "--"
    Const AccChars As String = "ŠŽšžŸÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðñòóôõöùúûüýÿ"
    Const RegChars As String = "SZszYAAAAAACEEEEIIIIDNOOOOOUUUUYaaaaaaceeeeiiiidnooooouuuuyy"
    For i As Integer = 1 To Len(AccChars)
    A = Mid(AccChars, i, 1)
    B = Mid(RegChars, i, 1)
    myString = Replace(myString, A, B)
    Next
    removeAccent = myString
    End Function
    I know that removing the accent changes the meaning of the word, but this is what the user wants so it's what I need to do. 
    Any help is greatly appreciated!! :)
    Thanks!
    Joni

    Finally got it to work.  I had to remove the first 5 characters from the replacement string (ŠŽšžŸ), couldn't find encoding that would handle these, and to be honest, I didn't really need them.  The important ones are still there, was probably
    just overkill on my part.
    UTF7 worked for the rest...
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim FileRdr As StreamReader = New StreamReader("m:\test\charReplace.txt", System.Text.Encoding.UTF7)
    Dim ReplaceWrtr As StreamWriter
    ReplaceWrtr = System.IO.File.CreateText("M:\test\CharReplaceOut.txt")
    Do While FileRdr.Peek() >= 0
    Dim currentRec As String = FileRdr.ReadLine
    removeAccent(currentRec)
    ReplaceWrtr.WriteLine(currentRec)
    Loop
    ReplaceWrtr.Close()
    End Sub
    'Replace foreign language characters with english characters
    Function removeAccent(ByRef myString As String)
    Dim A As String = "--"
    Dim B As String = "--"
    Const AccChars As String = "ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðñòóôõöùúûüýÿ"
    Const RegChars As String = "AAAAAACEEEEIIIIDNOOOOOUUUUYaaaaaaceeeeiiiidnooooouuuuyy"
    For i As Integer = 1 To Len(AccChars)
    A = Mid(AccChars, i, 1)
    B = Mid(RegChars, i, 1)
    myString = Replace(myString, A, B)
    Next
    removeAccent = myString
    End Function
    Thanks for all your help!  Greatly appreciated :)
    -Joni

  • How do I display text only in the first page inXML Publisher

    Hi everybody,
    I've been reading so much, on the last two days, on this issue at this forum but I didn't get an answer. My problem is: In an invoices report some text and fields from the invoice header, (such as payment terms, bank details etc.), should be printed only in the first page of the invoice, (If the invoice has more than one page). These elements are not in the document header/footer but in the document body. That's why I think the different fist page of MS Word will not work. I tried also <? start@first-page:body ?>, with no success. Any idea, someone?
    Thanks,
    Shimon

    Hi,
    Did you find solution to your problem? I am facing same issue and I want to know how you solved it? It would be great help.
    Thank you.
    Regards,
    Rahul

  • Text node not showing first line?

    I'm trying to figure out some unexpected behavior with the layout of Text. If I create an example program based on the API documentation
    http://java.sun.com/javafx/1.2/docs/api/javafx.scene.text/javafx.scene.text.Text.html
    Like so:
    Stage
        title: "Application title"
        width: 500
        height: 500
        scene: Scene
            content: [ Text {font: Font { size: 20 } content: "First row\nSecond row" }  ]
    }The resulting screen only shows "Second row", the first line is moved out of the screen above. I need to set y to 20 to show the first line.
    Is that normal?

    Right, Text nodes have an textOrigin, which is default set to the base line. That means that y=0 is just below the letters.
    But the behavior is unexpected when simply adding a Text node and nothing is visible.

Maybe you are looking for

  • How do I get Apple to stop sending me email?

    I know this isn't the right forum for this question, but I didn't see one that seemed relevant. My first question is regarding these discussion boards. I posted a question here (in the Using iPod Shuffle area) and since then, I am getting an email ev

  • I would like to know which model has been discontinued? is it EOS 600D or 650D?

    i would like to know which model has been discontinued? is it EOS 600D or 650D?  And is 650d at 1650 a good deal? 

  • Links in database

    I am trying to find out if it is possible to set up links in database (Appleworks 6), and if so, how. Right now, the links screen pops up, but won't actually let me do anything. Any suggestions?

  • Any idea what could have caused this screen issue?

    I was wiping off the keyboard on my Mac pro 1,1 and now the screen looks like the attached photo. I am running OS 10.7.5 and had no issues with the computer or the monitor until a few minutes ago It is a Gateway KX2153 monitor and I tried adjusting t

  • I need to see my agenda in the home screen

    i want t osee the next appointments in my home screeen with out having to check the calendar all time. I have upgraded to OS6 and since then the theme that is loaded does not support this.  is there any way to do this? Thanks