Perl:在regexmatch上方打印5行

时间:2016-09-12 18:03:10

标签: regex perl

我正在尝试从一个巨大的数据文件中打印“END”上方的5行。

有人可以帮忙吗?我的文件格式是

 --   Count .    .    .     . . .   .   .   .   .   .   . . . . . . . . . . . .  -------------------------------------    ------------------------------------------- 
00000001 0000 0000 00000 2 0 01c 01d 01c 01d 01c 01d 0 1 0 1 0 0 0 0 0 0 0 00 
00000002 0001 0000 00000 2 2 019 006 019 006 019 006 0 1 1 1 1 1 1 1 1 1 0 00
00000003 0002 0000 00000 2 0 00d 007 00d 007 00d 007 0 0 0 1 0 0 0 0 0 0 0 00
00000004 0003 0000 00000 2 2 00b 009 00b 009 00b 009 0 0 0 0 0 0 0 0 0 0 0 00 
00000005 0004 0000 00000 2 2 01a 008 01a 008 01a 008 0 0 0 0 0 0 0 0 0 0 0 00
END

2 个答案:

答案 0 :(得分:2)

只需使用grep:

    private ArrayList<MyStorage> foodintervallist_new = new ArrayList<MyStorage>();

     try{
        final String result = response.body().string();
    ///your code here is not good
        JSONObject jsonObject = new JSONObject(result);
        String data = jsonObject.getString("data");
    ////

        JSONArray foodintervalarray = new JSONArray(data);
        for (int j = 0; j < foodintervalarray.length(); j++) {
            JSONObject jsonObject1 = foodintervalarray.getJSONObject(j);
            final String food_interval = 
            jsonObject1.getString(FOOD_INTERVAL);
            Log.i("food_interval ", "food_interval " + food_interval);
            String item_name = jsonObject1.getString(ITEM_NAME);
            Log.i("item_name ", "item_name " + item_name);

    appendIfUniqueElement(item_name,food_interval);
            runOnUiThread(new Runnable() {
            @Override
            public void run() {

                ListViewAdapter listViewAdapter = new 
                ListViewAdapter(Diet_Order_Activity_New.this,
                foodintervallist_new);
                listView.setAdapter(listViewAdapter);                  
                listViewAdapter.notifyDataSetChanged();
              }
          });
    }
private void appendIfUniqueElement(String name, String food) {
boolean new_element = true;
for (int i = 0 ; i < foodintervallist_new.size() ; i++) {
if (appendIfSameName(name,food)) {
new_element = false;
break;
} else {
//add new
}

}
if (new_element )
foodintervallist_new.add(new MyStorage(name, food));
}

或者,您可以使用以下任一Perl单行:

grep END file -B 5

perl -ne'print @a if /^END$/; push @a, $_; shift(@a) if @a>5;' file

第二行打印匹配行,第一行不会。

答案 1 :(得分:1)

只需保留你在内存中读过的最后5行。

Sequel::Database