【问题标题】:Deleting the last occurence of a string in a file using java/shell使用 java/shell 删除文件中最后出现的字符串
【发布时间】:2013-09-25 12:43:19
【问题描述】:

需要删除文件中最后出现的字符串,即 VirtualHost。我可以使用java,shell来做到这一点。 文件结构是一个xml文件。我需要的是我需要将 VirtualHost 移到最后。所以我试图删除它然后追加。

 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> 

我尝试过这样做:

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

}

【问题讨论】:

  • 作为您的示例,您正在做两件事,移动 1 行并删除一个...您想要哪一个?
  • @Rayf plus,他并没有删除最后一个的出现,而是第一个LocationMatch....
  • 我需要删除文件中最后出现的VirtualHost并在最后移动它
  • 可以使用 sed 正则表达式完成吗?
  • 在我看来不像 XML。看起来像 Apache 配置

标签: java file shell sed


【解决方案1】:

您坚持使用 Java 的原因有哪些?

你可以用 sed 做到这一点:

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

这将产生整个文件内容减去&lt;/VirtualHost&gt;

然后只需在您的#Added for Patch 文本中包含&lt;/VirtualHost&gt;

【讨论】:

    【解决方案2】:

    使用可以提供 java 对象的 XML 解析器。然后从根遍历到想要的元素,就可以进行所有的操作了

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-05
      • 1970-01-01
      • 2012-04-14
      • 2023-01-24
      • 2016-05-27
      • 2012-05-31
      • 1970-01-01
      相关资源
      最近更新 更多