Match String and get line number and filename

Hi All,
I'm new to unix shell scripting.. Could someone guide me.

I have to search a string in the entire directory, once the search string is matched, it should print the line number of the string that matches and also the line and along with
it, it should print the file name.

Thanks,
Thenz

you may try this:

grep -n STRING_TO_SEARCH *

Hi,
Thanks for that code.
I tried the code but that is taking a longer time and i'm not getting anything.

I also tried this code, which is working but i wanted only to get the string and give me the line number and filename

#1/bin/sh
echo $PWD
echo "enter the string to search :"
read string
echo "enter the directory from the search to begin :"
read dir
find $dir -type f -exec grep $string {} \;

I'm not sure how to proceed to get the line number and filename.

below code search all the txt file in current folder, and any line match "pattern" will be printed together with the filename and line number

@files=glob("*.txt");
sub find{
	my $file=shift;
	open FH,"<$file";
	while(<FH>){
		print $file."->line ".$..":".$_ if (m/pattern/);
	}
	close FH;
}
foreach(@files){
	find($_);
}

You were almost there. First, add the filename:

find $dir -type f -exec grep $string {} \; -print

Then - you got that explained already - use "grep -n" to get the line numbers:

find $dir -type f -exec grep -n $string {} \; -print

I suggest reading a man page now and then if you encounter a program or a program call you don't understand fully, like the "-n" switch in "grep". You could have looked up "-n" on the man page of grep and find out this way what its purpose is. This is generally a fruititious approach.

I hope this helps.

bakunin

Hi All,

Thanks for all your replies and suggestion, I getting to what i wanted..
I have few questions which i would like to get clarified. I'm not sure how this function works..

@files=glob("*.txt");
sub find{
my $file=shift;
open FH,"<$file";
while(<FH>){
print $file."->line ".$..":".$_ if (m/pattern/);
}
close FH;
}
foreach(@files){
find($_);
}

Please explain me about " @files and open FH and foreach(@files){ find($_); } "

Thanks once again :slight_smile: