Extracting number from text files for variable

Hello again,
I have several different types of text files all with the line
# NPTS=32768  DT=0.005
somewhere in the file.  The numerical values are different for each file and I need to pull them out to assign as a variable for a program I am running.
How can I search a file and pull out each of these two numbers?
Thank you

Procyon's sed script assumes that the NPTS number and the DT number will both always have a period in them. In the original, the NPTS number doesn't have a period, and I don't know whether the DT number may lack a period.
You could try this instead (replacing the 's~....~p' part of Procyon's script):
's~# NPTS=\([0-9.]*\) *DT=\([0-9.]*\)~\1,\2~p'
That may let in stuff you want to exclude, for instance, it would let in:
NPTS=0.0.0.0.0 DT=1.1.1.1.1
and:
NPTS=....... DT=
and so on. But it's a tradeoff: if you know your data doesn't include anything like that, you can go with a simpler sed script. If you need to be fussier about what you're matching, then your sed script will need to be more complex.
EDIT: What I said in first paragraph is wrong. I overlooked the '*' after the '\.' in Procyon's script. What he's got will permit but not require a period. My final point still applies, though, to both of our suggestions. His script and my script would both match the second of my bad cases.
Last edited by Profjim (2008-09-17 21:31:34)

Similar Messages

  • API extracting keywods from text files

    hi all,
    i will be grateful if any of you can suggest some free java api which can be used to extract keywords from text files.
    thanx in advance
    malls

    java.util.regex - regular expressions API in JDK 1.4

  • How to find largest number from text file

    I am using the "Read from text file" block to read the data from my .txt file into labview.  It is now in string format.  I have many numbers in the file.  
    For example:
    0.45
    0.35
    0.12
    1.354
    1.56
    2.89
    5.89
    0.56
    That is what a text file might look like.  I want to find which of these numbers is largest, and do calculations with that number.  I am having trouble with strings/number formats/arrays, etc.  Thanks
    Solved!
    Go to Solution.

    The spreadsheet functions and VIs typically work on strings representing numbers separated by delimiters.  This is a typical way to save a "spreadsheet" (of numbers) to a text file, for example .csv files.  These are quite versatile and powerful functions.  Spend a bit of time becoming familiar with them because you may find yourself using them a lot.
    Lynn

  • How to extract data from  text file to database table

    Hi ,
    I am trying to upload  data in text file to database table  using GUI_UPLOAD function .what would be the program for that.
    thanks in advance.

    Hi,
    I don't think you have a standard sap program to upload data from file to database table...
    Instead you can create a custom program like this..
    DATA: T_FILEDATA(1000) OCCURS 0 WITH HEADER LINE.
    DATA: T_ZTABLE LIKE ZTABLE OCCURS 0 WITH HEADER LINE.
    CALL FUNCTION 'GUI_UPLOAD'
      EXPORTING
        filename                      = 'C:\TEST.TXT'
      tables
        data_tab                      = T_FILEDATA
    EXCEPTIONS
       FILE_OPEN_ERROR               = 1
       FILE_READ_ERROR               = 2
       NO_BATCH                      = 3
       GUI_REFUSE_FILETRANSFER       = 4
       INVALID_TYPE                  = 5
       NO_AUTHORITY                  = 6
       UNKNOWN_ERROR                 = 7
       BAD_DATA_FORMAT               = 8
       HEADER_NOT_ALLOWED            = 9
       SEPARATOR_NOT_ALLOWED         = 10
       HEADER_TOO_LONG               = 11
       UNKNOWN_DP_ERROR              = 12
       ACCESS_DENIED                 = 13
       DP_OUT_OF_MEMORY              = 14
       DISK_FULL                     = 15
       DP_TIMEOUT                    = 16
       OTHERS                        = 17
    IF sy-subrc <> 0.
    MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
            WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    ENDIF.
    LOOP AT T_FILEDATA.
      T_ZTABLE = T_FILEDATA.
      APPEND T_ZTABLE.
    ENDLOOP.
    MODIFY ZTABLE FROM TABLE T_ZTABLE.
    COMMIT WORK..
    Thanks,
    Naren

  • LabVIEW for ARM 2009 Read from text file bug

    Hello,
    If you use the read from text file vi for reading text files from a sdcard there is a bug when you select the option "read lines"
    you cannot select how many lines you want to read, it always reads the whole file, which cause a memory fault if you read big files!
    I fixed this in the code (but the software doesn't recognize a EOF anymore..) in CCGByteStreamFileSupport.c
    at row 709 the memory is allocated but it tries to allocate to much (since u only want to read lines).
    looking at the codes it looks like it supposed to allocated 256 for a string:
    Boolean bReadEntireLine = (linemode && (cnt == 0)); 
    if(bReadEntireLine && !cnt) {
      cnt = BUFINCR;    //BUFINCR=256
    but cnt is never false since if you select read lines this is the size of the file!
    the variable linemode is also the size of the file.. STRANGE!
    my solution:
    Boolean bReadEntireLine = (linemode && (cnt > 0));  // ==
     if(bReadEntireLine) {    //if(bReadEntireLine && !cnt) {
      cnt = BUFINCR;
    and now the read line option does work, and reads one line until he sees CR or LF or if the count of 256 is done.
    maybe the code is good but the data link of the vi's to the variables may be not, (cnt and linemode are the size of the file!)
    count should be the number of lines, like chars in char mode.
    linemode should be 0 or 1.
    Hope someone can fix this in the new version!
    greets,
    Wouter
    Wouter.
    "LabVIEW for ARM guru and bug destroyer"

    I have another solution, the EOF works with this one.
    the cnt is the bytes that are not read yet, so the first time it tries to read (and allocate 4 MB).
    you only want to say that if it's in line mode and cnt > 256 (BUFINCR) cnt = BUFINCR
    the next time cnt is the value of the bytes that are not read yet, so the old value minus the line (until CR LF) or if cnt (256) is reached.
    with this solution the program does not try to allocate the whole file but for the max of 256.
    in CCGByteStreamFileSupprt.c row 705
     if(linemode && (cnt>BUFINCR)){
       cnt = BUFINCR;
    don't use the count input when using the vi in line mode. count does not make sense, cnt will be the total file size. also the output will be an array.
    linemode seems to be the value of the file size but I checked this and it is just 0 or 1, so this is good
    update: damn it doesn't work!
    Wouter.
    "LabVIEW for ARM guru and bug destroyer"

  • Set a timeout for "read from text file"

    I Need to read from a text file on a remote pc and use the read from text file function to do this. It wotks but sometimes this pc is down causing long wait times in my vi.
    Is there a way to set a timeout for the read from text file function, or is there an other solution?
    Thank you

    You could check that the path is valid first before you attempt to read the file.  hen put the file read in a True-False case structure based on the results of the check.  You can use the function "Check if File or Folder Exists"  It checks whether a file or folder exists on disk at a specified path. This VI works with standard files and folders as well as files in LLB files.   The function is found in the File I/O --> Advanced File Functions palette.
    Tom

  • Code Challange - Code for extracting content from a file in KM

    Hi,
      I want to extract content from a file which is in KM Repository using the Webdynpro View.  I wrote the following code for the extraction. But it is throwing some exception.
    Code Written:
    <b>  
      URLConnection conn = null;
          DataInputStream data = null;
          String line;
          StringBuffer buf = new StringBuffer();
         wdContext.currentContextElement().setTextdisp("Hello");
         try {
          URL theURL = new URL("http://ctssap1:50000/irj/servlet/prt/portal/prtroot/com.sap.km.cm.docs/documents/News/New%20text.txt");     
            conn = theURL.openConnection();
           // conn.connect();
            wdContext.currentContextElement().setTextdisp("Inside Try");      
            data = new DataInputStream(new BufferedInputStream(
                               conn.getInputStream()));
            while ((line = data.readLine()) != null) {
               buf.append(line + "\n");
            data.close();
            String buffer = new String(buf);
            wdContext.currentContextElement().setTextdisp(buffer);
          catch (IOException e) {
              wdContext.currentContextElement().setTextdisp("IO Error:" + e.getMessage());
          }</b>
    Exception Got:
    <b>IO Error:Server returned HTTP response code: 401 for URL: http://ctssap1:50000/irj/servlet/prt/portal/prtroot/com.sap.km.cm.docs/documents/News/New%20text.txt</b>
    Can anyone help me out in this process... or please suggest some other way to extract the content.
    Thanks in Advance.
    Regards,
    Srinivas.

    Hi Srinivas,
    VaPath will have the path of ur document.
    Check this modified code snippet which will answer ur  questions and solve ur problem.
    IWDClientUser wdClientUser = WDClientUser.getCurrentUser();
    IUser sapUser = wdClientUser. getSAPUser();
    com.sapportals.portal.security.usermanagement.IUser ep5User = WPUMFactory.getUserFactory().getEP5User(sapUser);
    IResourceContext context = new ResourceContext(ep5User);
    /Specify the path of ur document here./
    RID pathRID = RID.getRID("/documents/file2");
    IResource resource = ResourceFactory.getInstance()
    .getResource(context);
    InputStream in = resource.getContent().getInputStream();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    byte[] buffer = new byte[4096];
    int bytesread = 0;
    while ((bytesread = in.read(buffer)) != -1) {
    out.write(buffer, 0, bytesread);
    String myData = out.toString();
    /*myFile will containS the content of the document./
    wdComponentAPI.getMessageManager().reportSuccess(myData);
    Hope this solves ur problem.
    Regards,
    Sowjanya.

  • Why does Read from Text file default to array of 9 elements

    I am writing to a text file starting with a type def. cluster (control) of say 15 dbl numeric elements, that works fine I open the tab-delimited text file and all of the elements appear in the file.  However when I read from the same text file back to the same type def. cluster (indicator), the read from text file defaults to 9 elements?? Is there a way to control how many elements are read from the file.  This all works great when I initially use a cluster of 9 elements and read back to a cluster of 9 elements.
    Solved!
    Go to Solution.

    From the LabVIEW Help: http://zone.ni.com/reference/en-XX/help/371361G-01/glang/array_to_cluster/
    Converts a 1D array to a cluster of elements of the same type as the array elements. Right-click the function and select Cluster Size from the shortcut menu to set the number of elements in the cluster.
    The default is nine. The maximum cluster size for this function is 256.
    Aside: so, how many times has this question been asked over the years?

  • Read from Text File - Help Bug?

    Hi - I am currently working on LV8 and I think that there is some misunderstanding potential in the help file. To be more exact in the help to the "Read From Text File" VI.
    The description for "count":
    " ... If count is <0, the function reads the entire file. The
    default is –1, which indicates to read a single line if you placed a checkmark
    next to the Read Lines shortcut menu item and to read the
    entire file if you removed the checkmark next to the item. "
    If count is lower than zero, the function reads the entire file. That sounds clear to me.
    The default is -1, which indicates to read a single line if you placed a checkmark next to the "Read Lines" shortcut menu item. Now what? Does it read a single line or the whole file?
    .. and to read the entire file if you removed the checkmark next to the item. I thought it reads the whole file if I use -1 ?
    the VI itself behaves as I'd expect it to:
    * If I place a checkmark next to Read Lines and put -1, I get an array containing the lines
    * If I remove the checkmark, I get only a single string item.
    Now where is the error? Is the VI not working properly or only the description a little bit ... strange ?

    ?hein??
    ?what?
    Both you guys lost me..
    And I drink coffee without sugar (being sweet enough, already) 
    Here is what I get from Context Help on the Read From Text File:
    Read from Text File
    Reads a specified number of characters or lines from a byte stream file. By default, this function reads all characters from the text file. Wire an integer value to count to specify how many individual characters you want to read starting with the first character. Right-click the function and place a checkmark next to the Read Lines option in the shortcut menu to read individual lines from the text file. When you select the Read Lines option in the shortcut menu, wire an integer value to the count input to specify how many individual lines you want to read from the file starting with the first line. Enter a value of -1 in count to read all characters and lines from the text file.
    Humm.
    New feature (again)..  If you select checkmark the Read Lines option, it will not send the text to a sting indicator, as shown in the attached image.  If selected, then it's expecting to write lines to an array of strings...  WHY???  I don't know..  I'll ask..
    Strange...  LV8 is full of mysteries... 
    RayR
    Attachments:
    bad write file.JPG ‏33 KB
    more bad write file.JPG ‏12 KB

  • Importing a text file with variable values into web reporting

    Hello,
    I'm looking for a possibility to import values from a text file into a variable selection in Web reporting.
    With BEx reporting in Excel this is possible, by clicking on the multiple selection button in the variable popup screen, and subsequently selecting the "Import from Text file" button.
    However, this function seems not to be available for web-reporting...
    It would be great if someone could help me out with this!
    Thanks & regards,
    Arvid

    Hi,
    we could resolve this issue, so i thought it may also be helpful for others:
    In our example we used a file with numbers for materials. This file is stored somewhere in a directory, to which SAP BI must have authorization to read.
    The file looks something like this:
    4711
    4712
    4713
    4714
    The file is named "import.txt" and lays in directory "/usr/sap/EC6/files/bi/"
    *&  Include           ZXRSRU01
    * global variables
    Data: intern_range LIKE LINE OF i_t_var_range,
          l_s_range    TYPE rsr_s_rangesid,
          line(100)    TYPE c,
          p_file(128)  TYPE c,
          length_rangelow  type i,
          tmp_rangelow     like l_s_range-low.
    * internal tables for selection-transfer from transaction
    * Data: BEGIN OF it_file occurs 0,
    *        it_p_file(128) TYPE c,
    *      END of it_file.
    IF i_step = 1.
    ** variables can be changed or set before pop-up appears
      CASE i_vnam.
    * take material from external file to selection-list
         WHEN 'ZSD_UPMA'.
    ** call of transaction, with which the path can be set
    *CALL TRANSACTION 'ZBW_VARIABLE' using it_file
    *MODE 'A'      " call should be visible, so that variable can be set
    *UPDATE 'S'.   " first transaction, then processing
    ** Der Pfad, der in dem Selektionsbild eingegeben wird, wird an die Variable übergeben
    ** Der Set-Parameter ist in Report ZSD_SELECT_VARIABLE
    *  get parameter id 'VAR' field p_file.
    p_file = '/usr/sap/EC6/files/bi/import.txt'.
    * further handling of variable in BI
          OPEN DATASET p_file FOR INPUT IN TEXT MODE ENCODING DEFAULT.
          IF sy-subrc = 0.
            READ DATASET p_file INTO line.
            WHILE sy-subrc = 0.
              IF line(2) <> '//'.
                l_s_range-sign = 'I'.
                l_s_range-opt  = 'EQ'.
                l_s_range-low  = line.
    * fill with leading Zeros
    * in variable tmp_rangelow the value from l_s_range-low is taken
        tmp_rangelow    = l_s_range-low.
    * read the length
        length_rangelow = strlen( tmp_rangelow ).
    * in our case: material has 18 characters
        while length_rangelow lt 18.
          CONCATENATE '0' tmp_rangelow INTO tmp_rangelow.
          length_rangelow = length_rangelow + 1.
        endwhile.
    * initialize l_s_range-low
        clear l_s_range-low.
    * set with filled values
        l_s_range-low = tmp_rangelow.
    * transfer to structure
                APPEND l_s_range TO e_t_range.
              ENDIF.
              READ DATASET p_file INTO line.
            ENDWHILE.
          ENDIF.
          CLOSE DATASET p_file.
        ENDCASE.
    ELSEIF i_step = 2.
    ** in step 2 all variable values from pop-up input can be processed or
    ** User Exit variables can be derived
    * UserExit Ende.
    ENDIF.
    Hope i could help!
    Best regards,
    Tobias

  • Hi, extract data from xml file and insert into another exiting xml file

    i am searching code to extract data from xml file and insert into another exiting xml file by a java program. I understood it is easy to extract data from a xml file, and how ever without creating another xml file. We want to insert the extracted data into another exiting xml file. Suggestions?
    1st xml file which has two lines(text1.xml)
    <?xml version="1.0" encoding="iso-8859-1"?>
    <xs:PrintDataRequest xmlns:xs="http://com.unisys.com/Anid"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://com.unisys.com/Anid file:ANIDWS.xsd">
    <xs:Person>
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://com.unisys.com/Anid file:ANIDWS.xsd">
    These two lines has to be inserted in the existing another xml(text 2.xml) file(at line 3 and 4)
    Regards,
    bubbly

    Jadz_Core wrote:
    RandomAccessFile? If you know where you want to insert it.Are you sure about this? If using this, the receiving file would have to have bytes inserted that exactly match the number of bytes replaced. I'm thinking that you'll likely have to stream through the second XML with a SAX parser and copy information (or insert new information) as you stream with an XML writer of some sort.

  • How to open saved files using 'read from text file' function

    Hi everyone, I am having a hard time trying to solve the this particular problem ( probably because I am a newb to lanbview ). Anyway , I am able to save the acquired waveforms by using the 'Write to text file' icon. I did manually modify the block diagram of the 'Write to text file' icon and create the correct number of connector so as to make my program work. But now I have no idea on how to modify the block diagram of the 'Read from text file' block diagram to make my program 'open' my saved waveforms. Or i do not have to modify anything from the block diagram of the 'Read from text file'? Can anyone teach/help me connect up? Do i need the build array on the "open" page?
    Here are some screenshots on part of my program  
    let me know if you guys would need more information / screenshots thank you!
    Attachments:
    ss_save.jpg ‏94 KB
    ss_open.jpg ‏94 KB
    modified_writetotextfile.jpg ‏99 KB

    Ohmy, thanks altenbach. oh yeah i forgot about those sub VIs. will upload them now. Was rather demoralized after reading the comments and really struck me on how weak i'm at on labview really hope to get this done. But of course i have to study through and see how it works. Actually i am going to replace those 'signal generators sub vi' with ThoughtTechonology's sample code so i can obtain data waveforms real-time using Electrocardiography (ECG) ,Electromyography (EMG ) and Electroencephalography (EEG) hopefully i can find out how to connect the sample code.
    ( ps . cant connect it now unless my program is working otherwise labview will crash ) 
    ( p.s.s the encoder of my biofeedback trainer already acts as an DAQ so i wont need to place an DAQ assistant in my block diagram i suppose )
    The sample code of ThoughtTechnology is named as attachment.ashx.vi. too bad i cant use it and present it as my project
    Attachments:
    frequency detactor.vi ‏53 KB
    signal generator.vi ‏13 KB
    attachment.ashx.vi ‏40 KB

  • Trying to parse a file-read from text file.vi

    I'm attempting to read a txt file that has tab separated data. In the fourth (or any) column is the only data I need. The data is a string of numbers (23.454).
    I've used the Read from Text File.vi and the Read From Spreadsheet.vi and I just don't seem to have enough LV background to extract the pertinent  data into a graph. any suggestions?

    (It is silly to use "delete from array" if all you want is a column. The correct function is "index array")
    Joe's idea above basically works fine. Here's a quick adapdation (the node before the graph is "index array" from the array palette.).
    Message Edited by altenbach on 06-11-2007 11:57 AM
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    FileRead.png ‏11 KB

  • Read from text file, display in textarea

    java newbie here - I'm trying to write a chat program that checks a text file every 1 second for new text, and then writes that text to a textArea. I've got the thread setup and running, and it checks and text file for new text - all that works and prints to system console - but I have no idea how to print that text to a textArea.
    I've tried textArea.append, but it seems this only works on the initial run - if I put it in the thread, it won't work. I can make textArea.append work if its in an ActionEvent - but how would I make an ActionEvent run only when my script detects new text from my text file?
    Any ideas on how to do this are appreciated.
    --Mike                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    I've tried textArea.append, but it seems this only works on the initial
    run - if I put it in the thread, it won't work. I can make textArea.append
    work if its in an ActionEvent - but how would I make an ActionEvent
    run only when my script detects new text from my text file? ?
    It doesn't matter if you call the textArea.append() when the ActionEvent is triggered or if you call textArea.append() directly from a thread or any other object, the text will be append to te text area. What could have happen is you somehow lost the reference pointing to the textArea that you add to your user interface.
    example:
    JTextArea txtArea = blah..blah..blah
    MyThread t = new myThread(txtArea);
    class MyThread extends Thread{
        private JTextArea txtArea;
        public MyThread(Thread textArea){
            this.textArea = textArea;
        public void run(){
            textArea = new JTextArea(); // opps..you lost the reference to the textArea in the main gui...what you have done is created a new JTextArea object and point to tat..and this textarea object is not visible.
    }

  • Read from text file vi won't read file...

    I am very new to LV programming so I hope you forgive any stupid mistakes I am making.   I am using Ver. 8.2 on an XP machine.
    I have a small program that stores small data sets in text files and can update them individually or read and update them all sequentially, sending the data out a USB device.   Currently I am just using two data sets, each in their own small text file.  The delimiter is two commas ",,".
    The program works fine as written when run in the regular programming environment.   I noticed, however, as soon as I built it into a project that the one function where it would read each file sequentially to update both files the read from text file vi would return an empty data set, resulting in blank values being written back into the file.   I read and rewrite the values back to the text file to place the one updated field (price) in it'sproper place.  Each small text file is identified and named with a 4 digit number "ID".   I built it twce, and get the same result.  I also built it into an installer and unfortunately the bug travelled into the installation as well.
    Here is the overall program code in question:
    Here is the reading and parsing subvi:
    If you have any idea at all what could cause this I would really appreciate it!
    Solved!
    Go to Solution.

    Hi Kiauma,
    Dennis beat me to it, but here goes my two cents:
    First of all, it's great to see that you're using error handling - that should make troubleshooting a lot easier.  By any chance, have you observed error 7 when you try to read your files and get an empty data set?  (You've probably seen that error before - it means the file wasn't found)
    If you're seeing that error, the issue probably has something to do with this:
    Relative paths differ in an executable.  This knowledge base document sums it up pretty well. To make matters more confusing, if you ever upgrade to LabVIEW 2009 the whole scheme changes.  Also, because an installer contains the executable, building the installer will always yield the same results.
    Lastly, instead of parsing each set of commas using the "match pattern" function, there's a function called "spreadsheet string to array" (also on the string palette) that does exactly what you're doing, except with one function:
    I hope this is helpful...
    Jim

Maybe you are looking for