Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
364 views
in Technique[技术] by (71.8m points)

Deleting the last occurence of a string in a file using java/shell

need to delete the last occurence of a string i.e. VirtualHost in a file. I can do it using java, shell. The file structure is an xml file. What I need is I need to shift the VirtualHost to the end. So I am trying to remove it and then append.

 Current Text:
    </VirtualHost>
    #Added for Patch 
    <LocationMatch ^/bea_wls_internal/>
    RewriteOptions inherit
    </LocationMatch>







Desired Text:
#Added for Patch
<LocationMatch ^/bea_wls_internal/>
RewriteOptions inherit
</LocationMatch>
</VirtualHost> 

i tried to do this:

    int c=1,i=1;
    int loc[]=new int[10];
    //String str="</VirtualHost>";
    BufferedReader br= new BufferedReader (new FileReader ());
    String line=br.readLine();
    FileWriter fw=new FileWriter(file_location);
    PrintWriter pw=new PrintWriter(fw);
    List<String> lines = new ArrayList<String>();

    while ((line != null)){
            //System.out.println(line);
            lines.add(line);
            c++;
            line=br.readLine();
    }
    br.close();
    int size=lines.size();
    System.out.println("size "+size);

    while(c>i){
        int filesize=lines.size();
        System.out.println(filesize);

        String str=lines.get(filesize-i);
        System.out.println(str);
        lines.remove(filesize-i);
        if (!lines.equals("</VirtualHost>")){
            System.out.println("inside if");
            lines.add(str);
            //break;
        }
        else if(lines.equals("</VirtualHost>")){
            break;
        }
        i++;
    }
    for (String writeLine : lines)
            pw.println(writeLine);


    pw.append("</VirtualHost>");
    pw.flush();
    pw.close();
    fw.close();
    System.out.println(c);
}

}

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Any reason you're insisting on using Java?

You could do this with sed:

sed '/</VirtualHost>/,$d' filename

This will produce the entire file contents minus the </VirtualHost>.

Then just include the </VirtualHost> in your #Added for Patch text.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...