Read the first word of each line in a text file

i need to read the first word of each line of a text file.
i know of line.split() but not actually sure how i would go about using it
Any help most appreciated
Many Thanks
Ben

Hi thanks for the reply!
this is what i tried... and it still doesn't get me the first word of each line!
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.io.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.swing.text.*;
import javax.swing.event.*;
import java.util.Calendar;
import java.util.Scanner;
import java.util.Vector;
import java.text.SimpleDateFormat;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.io.BufferedReader;
public class testing {
     Vector progs=new Vector();
     Vector rand=new Vector();
     String[] tmp = new String [2];
     String str;
     String str2="ewerwer";
     String str3;
     public void programTest()
               try
                         BufferedReader in = new BufferedReader(new FileReader("progList.log"));
                         while ((str = in.readLine()) != null)
                              progs.add(str);
                    catch(IOException e)
                         System.out.println("cannot read file");
     //////THE ISSUES IS HERE....I WANT TO GET THE FIRST WORD FROM EACH LINE OF THE FILE!!!     
          try
                         BufferedReader in2 = new BufferedReader(new FileReader("eventLog.log"));
                         while ((str = in2.readLine()) != null)
                              tmp = str.split(" ");
                              System.out.println(tmp[0]);
                    catch(IOException e)
                         System.out.println("cannot read file");
public static void main(String[] args)
             testing B = new testing();
             B.programTest();
           //  B.fileToVector();
             //B.LoginWindow();
           //B.anomDetect();
}//end class

Similar Messages

  • Select first word in each line of a text file to do something.

    How do I select the first word in each line to do something newer from a text file in Powershell?
    Example:
     GBL                            Primary    File            
     local                          Primary    File            
     localhost                      Primary    File            
     Opstest                        Primary    File            
     TrustAnchors                   Primary    File            
    99upgrade

    Hi 99,
    here's an example on how to do it:
    $lines = Get-Content "C:\ExampleFolder\Example.txt"
    foreach ($line in $lines)
    Write-Host ($line.Split(" "))[0]
    Just replace the Write-Host line in the loop with what you actually want to do with the first word in the line.
    Cheers,
    Fred
    There's no place like 127.0.0.1

  • Program to read only specific words in each Line in a text file

    Hi
    I have a question
    I need to write a program where the program must read only specific words in each line
    I will give you an example...
    PSAPPSRV.21201      1-42 13.35.54 238.360 Cur#1.HDEV RC=0 Dur=0.000 COM Stmt=SELECT VERSION FROM PSVERSION WHERE OBJECTTYPENAME = 'SYS'
    PSAPPSRV.21201      1-43 13.35.54 0.040 Cur#2.HDEV RC=0 Dur=0.000 COM Stmt=SELECT STYLESHEETNAME FROM PSOPTIONS
    These are two lines in my text file...now I need to read only the SQL statements present that is both SELECT statements.. Can you please suggest a method.......

    My first reaction to the question is why would you want such thing, but may be I am unknown :)
    Assuming you have the text as string, I mean
    String str = "PSAPPSRV.21201 1-42 13.35.54 238.360 Cur#1.HDEV RC=0 Dur=0.000 COM Stmt=SELECT VERSION FROM PSVERSION WHERE OBJECTTYPENAME = \'SYS\'";you can obtain the sql statement using substring method like
    String result = str.substring(str.indexOf("SELECT")); Again I assume there is no word SELECT preceding and the word SELECT is all caps.

  • Script to get the first word on each page

    Is there a script that would make a list of the first word of each page (or, preferably, create a text box on each page and place the next page's word in that)? My document's all in one story with one text frame on each page, although there are several other frames (header, page number) applied through master pages.

    You wrote:  I changed the numbers to "8.0425in",  "4.5681in",  "8.1275in", "5.4319in" and it mostly worked - it placed the box at exactly 5 inches (X) and at 8.085 inches (Y) instead of 4.5681 inches. Any idea why?
    No. I cannot reproduce the error you describe. I assume you've checked your numbers very closely in the script--I don't normally indicate measurements as strings.
    you wrote: Something wasn't working with the styling - it kept freezing the program -
    What do you mean by "freezing the program"? Is there a specific error message?
    The paragraph style is named "firstword" and is all lowercase letters?
    firstword paragraph style is NOT in a paragraph style group, right?
    Is the first word on any page too long when formatted with the paragraph style "firstword" to fit in the text frame?

  • Unwelcome caps on first word of each line in Pages 08

    I'm brand new to Pages, though I've used AppleWorks for years.
    I've searched exhaustively in "helps" for a/the way to disable the quirk of changing
    the first letter of each line of copy to a cap when typing. (We still 'type' here in the
    cornfields) I Would appreciate greatly, your help in finding an escape.
    Thank you for any help,
    ps

    Welcome to the Discussions!
    When you go to:
    Pages > Preferences > Auto-Correction (Tab)
    Is your Fix Capitalization box checked?
    Joe

  • How do you auto capitalize in the new version of pages? It no longer capitalizes the first word in each sentence and "I".

    I just updated to the new version, and this problem occurred right away. Please help!! 

    Congratulations on discovering the first of over 90 + features removed from Pages by Apple:
    http://www.freeforum101.com/iworktipsntrick/viewforum.php?f=22&mforum=iworktipsn trick
    Your previous version of Pages should still be in your Applications/iWork folder. It actually works.
    Peter

  • Java write/append to each line of a text file

    I have spent numerous hours trying to figure out what I am doing wrong. If anyone more experienced could tell me what is wrong with my code.
    I have a very simple text file with 5 lines:
    line1
    line2
    line3
    line4
    line5
    All I am trying to do is append some string to the end of each of those lines. Everytime I run my code, it erases all content but does not write/append anything to the file. Any help is greatly appreciated.
    Thanks! I am about to throw this monitor out the window!!
    package Chapter6;
    import java.io.*;
    public class fileNavigation2 {
         public static void main(String[] args) {
              File dir = new File("C:\\testing");
              System.out.println(dir.isDirectory());
              try {
                   File file = new File(dir, "Test.txt");
                   FileReader fr = new FileReader(file);
                   BufferedReader br = new BufferedReader(fr);
                   FileWriter fw = new FileWriter(file);
                   BufferedWriter bw = new BufferedWriter(fw);
                   String s = "Add1,";
                   String s2 = "Add2\n";
                   String str;
                   while((str = br.readLine()) != null) {
                   StringBuffer sb = new StringBuffer(str);
                   sb.append(s + s2);
                   String y = sb.toString();
                   System.out.println(sb);
                   System.out.println("Appending");
                   bw.write(y);
                   bw.close();
                   System.out.println("Done");
              }catch(IOException e) {}
    }

    First, thanks a lot for your feedback. The code makes a lot of sense but it does not update the content of my Test.txt file.
    I only edited the line of code that creates the new file so that it could find the location of the file.
    Scanner file = new Scanner(new File("C:\\testing",fileName));==============================
    The code now looks like:
    import java.io.*;
    import java.util.*;
    public class Main {
        static void appendTo(String fileName, String[] newLines) throws IOException {
            List<String> allLines = getLinesFrom(fileName);
            for(String line : newLines) {
                allLines.add(line);
            writeLinesTo(fileName, allLines);
        static List<String> getLinesFrom(String fileName) throws IOException {
            List<String> lines = new ArrayList<String>();
            Scanner file = new Scanner(new File("C:\\testing",fileName));
            while(file.hasNextLine()) {
                lines.add(file.nextLine());
            file.close();
            System.out.println(lines);
            return lines;
        static void writeLinesTo(String fileName, List<String> lines) throws IOException {
            BufferedWriter out = new BufferedWriter(new FileWriter(fileName));
            for(String line : lines) {
                out.write(line);
                out.write(System.getProperty("line.separator"));
            out.close();
        public static void main(String[] args) {
            String fileName = "Test.txt";
            String[] extraLines = {
                    "a new line",
                    "and yet another new line"
            try {
                appendTo(fileName, extraLines);
                System.out.println("Done.");
            } catch (IOException e) {
                e.printStackTrace();
    }Again, thanks for the help.

  • Read the first string in the line, skipping the whitespace ---Possible???

    I am parsing through the following file:
          * AOCSOnLupda.h
          *  Created on: 20.07.2010
          *      Author: perv_na
    #ifndef AOCSONLUPDA_H_
    #define AOCSONLUPDA_H_
    // holds the value of on_lupda
    namespace AOCS {
         class AOCSOnLupda{
              private:
                    /* public part
              public:
    #endif /* AOCSONLUPDA_H_ */My main task is to, go inside this file, check if the namespace and class name provided by the user matches the one's inside this file. And then write a boolean initialization (e.g. boolean checked = 1).
    The problems I am facing is that, when I read through each line I want to make sure that there is no Block Comment signs or // sign in the beginning of the line. So that I am sure that I am not writing the initialization inside a comment line or something.
    My problem is I am not at all being able to read the first word of a line (without the whitespace).
    Can someone please tell me how you can skip the first whitespaces in a newly read line, and retrieve the first chars/String? Like in the line:
                   /* public part
              public:there is white space before the start and end of the block comment. And also in front of the word "public:"
    How do I get my hands on the start and end of block comment character and also "public:" by skipping the white spaces in front?
    Thank you
    newbie
    Edited by: JFC_newbie on Jul 27, 2010 8:46 AM

    Hi,
    thank you for the link ... but I am actually trying to do by myself.
    BufferedReader in;
              String lineInFile;
              try {
                   in = new BufferedReader(
                             new FileReader(
                                       "C:/Users/jui/Eclipse/eclipse-java-helios-win32-x86_64/javaWorkspace/FilePathSearchCreateTest/aocsFiles/AOCSOnLupda.h"));// open
                   while ((lineInFile = in.readLine()) != null) {
                        if((lineInFile.trim().length())!=0){   //If not a Blank Line then...
                        *     //Read the first non-whitespace char in the read line                         *                     
                             String [] tempLine = lineInFile.split("\\s");
                             System.out.println(tempLine[0]);
                   in.close();// safely close the BufferedReader after use
              } catch (IOException e) {
                   System.out.println("There was a problem:" + e);
              }But it's not working. I need my code to read the first char/String in a newly read line, by skipping the first whitespaces.
    Would really really appreciate some tips. thank you.

  • Is there a way to capitalize just the first word on a sentence on Pages v5.2?

    I'm sort of new to iwork, but i've been working with word for a long time and i know it very well.
    In word there is a tool in which you select a paragraph and you can capitalize the first word of each sentence.
    Is there a way i can do the same with pages v5.2? Pages would only let me capitalize each word of the selected paragraph.
    Thanks

    The previous major version of Pages (Pages '09 version 4.3) could automatically capitalize the first word of each sentence as you typed. That capability and a number of others was lost with the release of Pages v 5. You may still have the older version available in your Applications folder. You may also want to switch to Word or Open Office (free), both of which will likely be more familiar if you have worked with Word before.

  • Mail - Auto capitalize first word in each sentence

    When composing a message in mail is there a way to turn on auto capitalization for the word beginning each sentence?

    As far as I can tell you cant auto capitalize the first word of each sentence. I did however find out how to turn "i" into "I in case that is bugging you as well
    Go into System Preferences
    Click on Language and Text
    Choose the "Text" box on the menu bar
    It will bring you to the text substitution thingamajig where you can replace "i" with an "I". Once done it will work on Mail as well as most applications system wide.
    Hope that helps a little

  • How to capitalize the first letter of each  word in a sentence?

    Can anyone please explain how to split a sentence at a comma, or space or hyphen in to words and capitalize the first letter of each word. But I don't know how many words the sentence contains.

    HI,
    data : begin of itab occurs 0,
             words(40),
             end of itab.
    data : v_sentence(1000).
    data : lv_firstchar.
    split v_sentence at ',' into table itab.
    loop at itab.
    translate itab-words+0(1) to upper case.
    modify itab index sy-tabix.
    endloop.

  • Is there a command to capitalize the first letter of each word?

    That is to say, can you capitalize the first letter of each word in a document like say, word? Or using the net?
    Thanks guys.
    (hope that makes sense.)

    Select the text, then Format->Change Case->Title Case (Word 2004).

  • Read the first line of the table.

    Hi,
    Can you pls let me know as to how I read the first line of the table.
    Thx.

    hi check this.
    data: begin of itab occurs 0,
            matnr like mara-matnr ,
            meins like mara-meins,
            end of itab.
    select-options: s_matnr for mara-matnr .
    select matnr
             meins
             from mara
             into table itab
             where matnr in s_matnr .
    read table itab index 1 .
    loop at itab .
    write:/ itab-matnr .
    endloop .
    regards,
    venkat.

  • TS1702 Hi,  I downloaded Wild to my Ipad and I'm having issues.  I've only read the first few chapters but at the end of each chapter the last page is duplicated for 10 pages and then it goes to the next chapter.

    I downloaded Wild to my Ipad and I'm having issues.  I've only read the first few chapters but at the end of each chapter the last page is duplicated for 10 pages and then it goes to the next chapter.

    Quit the iBooks app completely and restart the iPad. Go to the home screen first by tapping the home button. Double tap the home button and the task bar will appear with all of your recent/open apps displayed at the bottom. Tap and hold down on any app icon until it begins to wiggle. Tap the minus sign in the upper left corner of the app that you want to close. Tap the home button or anywhere above the task bar. Restart the iPad.
    Restart the iPad by holding down on the sleep button until the red slider appears and then slide to shut off. To power up hold the sleep button until the Apple logo appears and let go of the button.
    Or ....Reset the iPad by holding down on the sleep and home buttons at the same time for about 10-15 seconds until the Apple Logo appears - ignore the red slider - let go of the buttons.
    Or ... Delete the book and download it again in the purchased tab of the iBook Store, as long as you use the same Apple ID, there is no charge to download it again.

  • Styling first letter in each line differently [was: Dreamweaver cs4 question]

    I am trying to change the font in a group of text, I want to change the first letter of each sentence to a large size and different color and when I do this it changes the entire  paragraph in the div, so how can I change the attribute of one letter in a word? Example: See how the first letter of each sentence spells out earth?  I want to make those letters to stand out.  CAN ANYONE TELL ME HOW TO DO THIS??????
    Ensuring compliance with relevant environmental legislation and regulations.
    Achieving and reviewing our set objectives and goals with continual improvements.
    Reducing environmental pollution by reducing, recycling and re-using by-products and waste.
    Training and communication to all our staff to participate and achieve environmental excellence.
    Having our environmental policy documented, implemented, maintained and made available to the public and interested third parties.
    Thank you in advance
    [Subject line edited for clarity by moderator]

    Your question went unanswered for nearly a day because of the meaningless subject line you used. Please take a moment to read How to get help quickly.
    There are a couple of ways to achieve what you want. The way I would do it is to make each line a separate paragraph, and wrap them in a div with an ID called "earth". The following CSS style rule will make the first letter of each paragraph 24px tall and green:
    #earth p:first-letter {
      color:#090;
      font-size:24px;
    This uses the first-letter pseudo-element and applies it to all paragraphs in the earth div.

Maybe you are looking for

  • Campaign Metrics - # Bounces Switched?

    Hi - We have sent out several campaigns and are now reporting on them. The metrics seem to be mixed up on the subject area. The campaign was sent out 2/3/2011 The receipent data on the campaign object shows delivery status of 8 hard bounces and 1 sof

  • Error while running the program of deferred Tax ( New)Program Name RFUMSV50

    Hi I am getting the error while running the program of deferred Tax ( New) Following is the detailed error : Enter rate / INR rate type M for 00.00.0000 in the system settings Message no. SG105 Diagnosis For the conversion of an amount into another c

  • The update "Mac OS X Update" can't be saved.  ERROR

    Hi, I have been searching these forums for an answer. Today I had a pop up informing me that update are available. Mac OX X Update 10.5.7.286 MB The 10.5.7 Update is recommended for all users running Mac OS X Leopard and includes general operating sy

  • Purchasing Group problem

    Hi all, we have implemented SRM 4.0 with CCM 2.0 in extended classic scenario. Therefor we have created 3 local purchasing groups. My question is which setting controls which purchasing group is chosen by creating a shopping cart? BR, Bernd

  • Alerts configuration in XI

    Hi All, Could you pls let me know about the Alerts configuration steps in detail or pls let me know use full links Thanks in advance, Nousheen.