尝试两个参数传递给调用的脚本的模式搜索 [英] Attempting to pass two arguments to a called script for a pattern search

查看:99
本文介绍了尝试两个参数传递给调用的脚本的模式搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法得到一个脚本做我想做的。

I'm having trouble getting a script to do what I want.

我有一个脚本,将搜索一个文件的模式和打印模式的行号和实例。

I have a script that will search a file for a pattern and print the line numbers and instances of that pattern.

我想知道如何使它先打印文件名,它打印找到了前行

I want to know how to make it print the file name first before it prints the lines found

我也想知道如何编写一个新的脚本,将调用这一个,并传递两个参数给它。

I also want to know how to write a new script that will call this one and pass two arguments to it.

的第一个参数是用于grep的图案和所述第二位置。

The first argument being the pattern for grep and the second the location.

如果该位置是一个目录,它将循环和搜索上使用脚本目录中的所有文件的模式。

If the location is a directory, it will loop and search the pattern on all files in the directory using the script.

#!/bin/bash

if [[ $# -ne 2 ]]
then
  echo "error: must provide 2 arguments."
  exit -1
fi

if [[ ! -e $2 ]];
then
    echo "error: second argument must be a file."
    exit -2
fi

echo "------ File =" $2 "------"
grep -ne "$1" "$2"

这是我使用,我需要新的调用脚本。我只是得到了很多帮助,从问过类似的问题,但我仍然是那种失去。我知道我可以使用-d命令来测试目录,然后使用'为'循环的命令,但究竟如何并不淘洗出我。

This is the script i'm using that I need the new one to call. I just got a lot of help from asking a similar question but i'm still kind of lost. I know that I can use the -d command to test for the directory and then use 'for' to loop the command, but exactly how isn't panning out for me.

推荐答案

的grep 有一个选项 -r 这可以帮助您避免第二个参数是一个目录,并使用循环来迭代该目录中的所有文件进行测试。

grep has an option -r which can help you avoid testing for second argument being a directory and using for loop to iterate all files of that directory.

页:

-R,-r,--recursive
               递归搜索子目录上市。

-R, -r, --recursive Recursively search subdirectories listed.

这也将打印的文件名。

It will also print the filename.

[JS웃:~/Temp]$ grep -r '5' t
t:5 10 15
t:10 15 20

[JS웃:~/Temp]$ grep -r '5' perl/
perl//hello.pl:my $age=65;
perl//practice.pl:use  v5.10;
perl//practice.pl:@array = (1,2,3,4,5);
perl//temp/person5.pm:#person5.pm
perl//temp/person9.pm:   my @date    = (localtime)[3,4,5];
perl//text.file:This is line 5

这篇关于尝试两个参数传递给调用的脚本的模式搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆