目标:echo"test\n\string\nfor\ngrep"|grep"string",将echo后面的字符串打印内容作为grep的输入参数,会打印出含有string的行
首先先创建一个txt文档
如何创建我上一篇博客里有
比如我们创建一个hello文档
因为它让输出的是含有string 的行所以hello文档就随便写几个含有string的语句来进行测试就行了
如:
接下来就开始写代码了,因为打印的目标为string所以我们要对test\n\string\nfor\ngrep进行切片处理只截取出string出来就行了
代码是这样的:
String patten=null;
System.out.print("输入:");
Scanner input=new Scanner(System.in);//输入要找寻输出的目标
patten=input.nextLine();
patten=patten.substring(7,13);//截取输入的目标中的7-13,作为要打印的目标
找到要打印的目标了我们就要开始在文档中找寻这个目标了
这个部分的代码是这样的
public static void Grep(String patten,String path)throws IOException{
int LineNumber=0;//定义行数
Pattern r=Pattern.compile(patten);//使要查找的目标等于r
File sum=new File(path);
InputStreamReader read=new InputStreamReader(new FileInputStream(sum));
BufferedReader num=new BufferedReader(read);
String line=null;
System.out.println("含有string的行有:");
while((line=num.readLine())!=null) {//判断文件的是否为空,只要不为空就一直查找
LineNumber++;
Matcher m = r.matcher(line);//在每一行找寻目标
if (m.find()) {//如果找到
System.out.println(LineNumber + " " + m.group());//就输出目标和行数
这样主要的任务大概就完成了
我们附上完整代码:
import java.io.IOException;
import java.util.Scanner;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class grep {
public static void main(String[] args)throws IOException{
String patten=null;
System.out.print("输入:");
Scanner input=new Scanner(System.in);//输入要找寻输出的目标
patten=input.nextLine();
patten=patten.substring(7,13);//截取输入的目标中的7-13,作为要打印的目标
Grep(patten,"/home/fxl/hello.txt");//调取文件的地址
System.out.println(patten);//输出要找寻的目标
}
public static void Grep(String patten,String path)throws IOException{
int LineNumber=0;//定义行数
Pattern r=Pattern.compile(patten);//使要查找的目标等于r
File sum=new File(path);
InputStreamReader read=new InputStreamReader(new FileInputStream(sum));
BufferedReader num=new BufferedReader(read);
String line=null;
System.out.println("含有string的行有:");
while((line=num.readLine())!=null) {//判断文件的是否为空,只要不为空就一直查找
LineNumber++;
Matcher m = r.matcher(line);//在每一行找寻目标
if (m.find()) {//如果找到
System.out.println(LineNumber + " " + m.group());//就输出目标和行数
}
}
}
}
运行的结果是这样的: