Deleting the last occurence of a string in a file

2020-01-19 07:11发布

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);
}

}

2条回答
看我几分像从前
2楼-- · 2020-01-19 07:47

Use XML parser which can provide the java object. Then traverse from root to desired element and you can perform all manipulation

查看更多
冷血范
3楼-- · 2020-01-19 07:58

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.

查看更多
登录 后发表回答