Attempting to pass two arguments to a called scrip

2019-08-17 06:13发布

问题:

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.

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"

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.

回答1:

I think you just want to add the -H option to grep:

   -H, --with-filename
          Print the file name for each match.  This is the default when there is more than one file to search.


回答2:

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.

From the man page:

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

It will also print the filename.

Test:

On one file:

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

On a directory:

[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