java对echo和grep功能实现的结合(两者结合)

题目要求:echo “test\n\string\nfor\ngrep" |grep “string”。 这条语句将echo 后面的
字符串打印内容作为grep的输入参数,会打印输出含有string的行
用java实现了类似功能
题目分析:1.输入一个字符串取其字串
调用字符串截取函数substring(begin_index,end_index)
2.java实现grep功能,写一个Grep函数
3.将截取的字串作为参数传入Grep函数
代码:
字符串输及截取:

        String pattern=null;
        System.out.println("please input");
        Scanner input=new Scanner(System.in);
        pattern=input.nextLine();
        pattern=pattern.substring(7,13);

Grep函数

  public static void Grep (String pattern,String path) throws IOException   //pattern为所匹配的字符串,path为文件地址
        {   int number=0;//表示行数
            Pattern r = Pattern.compile(pattern);
            File file=new File(path);
            InputStreamReader read = new InputStreamReader(new FileInputStream(file));
            BufferedReader bufferedReader = new BufferedReader(read);//创建一系列类
            String line = null;
            System.out.println("含有string的行有:");
            while ((line=bufferedReader.readLine()) != null)
            {   number++;
                Matcher m=r.matcher(line);
                if(m.find())
                {
                    System.out.println(number+"."+m.group());
                }
            }
        }

完整代码

package com.company;

import java.util.Scanner;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {

    public static void main (String[] args)throws IOException
    {   String pattern=null;
        System.out.println("please input");
        Scanner input=new Scanner(System.in);
        pattern=input.nextLine();
        pattern=pattern.substring(7,13);
        Grep(pattern,"/home/zyf/桌面/string.txt");


    }
    public static void Grep (String pattern,String path) throws IOException
    {   int number=0;
        Pattern r = Pattern.compile(pattern);
        File file=new File(path);
        InputStreamReader read = new InputStreamReader(new FileInputStream(file));
        BufferedReader bufferedReader = new BufferedReader(read);
        String line = null;
        System.out.println("含有string的行有:");
        while ((line=bufferedReader.readLine()) != null)
        {   number++;
            Matcher m=r.matcher(line);
            if(m.find())
            {
                System.out.println(number+"."+m.group());
            }
        }
    }
}

运行结果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值