テキスト置換
javaで書いてみた。思いのほかてこずった・・・やっぱりテキスト処理は結構独特だと思う。時間があればアルゴリズムを勉強してみたいな。
package fileinsert; import java.io.*; public class Main { public static void main(String[] args){ if(args.length < 2){ System.out.println("引数が足りません。"); System.exit(-1); } insert ins = new insert(args[0], args[1]); ins.exe(); } } /** targetファイルの内容を、insertファイルの指示(行数指定)に従って、置換挿入する。 */ class insert { BufferedReader target;// 挿入されるファイル int target_line=0; // バッファの指している行数 BufferedReader insert;// 置換するファイル public insert(String targetname, String insertname){ try{ target = new BufferedReader(new FileReader(targetname));// 挿入先ファイル insert = new BufferedReader(new FileReader(insertname));// 挿入元ファイル } catch(Exception e){ e.printStackTrace(); } } public void exe(){ while(updateInsert() == 0); } // 新しく挿入位置を読み込む // private int updateInsert(){ String str=null; int haihun = 0;// -の位置 // #で開始されていれば、位置指定の行 while(true){ try{ str = insert.readLine(); } catch(IOException e){ e.printStackTrace(); } if(str == null){//挿入するファイルがなくなったら。 targetprint(Integer.MAX_VALUE);//元のファイルを全部書き出す。 return -1; } else if(str.length() == 0 ||str.charAt(0) != '#'){ System.out.println(str); } else { break; } } haihun = str.indexOf('-'); if(haihun == -1){ String linenumber = str.substring(1,str.length()); targetprint(Integer.parseInt(linenumber)-1); } else { String linenumber = str.substring(1,haihun); targetprint(Integer.parseInt(linenumber)-1); linenumber = str.substring(haihun+1,str.length()); targetskip(Integer.parseInt(linenumber)); } return 0; } //line行まで、targetファイルを書き出す。 private void targetprint(int line){ try{ for(int i=target_line;i<line;i++){ String str = target.readLine(); if(str == null){ return; } System.out.println(str); } target_line = line; } catch(IOException e){ e.printStackTrace(); } } // line行まで、targetファイルを読みとばす。 private void targetskip(int line){ try{ for(int i=target_line;i<line;i++){ target.readLine(); } target_line = line; } catch(IOException e){ e.printStackTrace(); } } }
ざっとこんな感じで。
public class hello { public static void main(String[] args){ System.out.println("hello."); } }
こういうのがあったとして、
#3 System.out.println("world."); #4-4 }// こめんと
これを指定してやれば、
public class hello { public static void main(String[] args){ System.out.println("world."); System.out.println("hello."); }// こめんと }
こんなんがでてくる。
つまり、挿入側の#数字を見ていて、数字の行数の位置に挿入しているのだ。
"-"(ハイフン)をつかって範囲指定するとその部分と置換するようになっている。
同じ行数を指定すれば、その行と入れ替えが行える。
あー、なんかこういうのありそう。。。どっかないのかなー。