1829467 Members
1607 Online
109991 Solutions
New Discussion

grep to show filename

 
SOLVED
Go to solution
Dave Chamberlin
Trusted Contributor

grep to show filename

I am trying to locate certain strings in a group of binary files - but I want the filename for each found string. This: strings -a *.xxx | grep mystring - shows the strings, but without filenames. The grep -n option does not provide filenames. Any ideas?
6 REPLIES 6
KapilRaj
Honored Contributor

Re: grep to show filename

for file in `ls *.xxx`
do
strings -a $file | grep my string > /tmp/log$$
if [ $? -eq 0 ]
then
echo "$file has" `cat /tmp/log$$`
>/tmp/log$$
fi
done
rm -rf /tmp/log$$
Nothing is impossible
James R. Ferguson
Acclaimed Contributor

Re: grep to show filename

Hi Dave:

One way:

cd /path
for F in `ls -1`
do
echo "[ $F ]"
strings $F|grep pattern
done

Regards!

...JRF...

Dennis Handly
Acclaimed Contributor

Re: grep to show filename

>grep -n option does not provide filenames

Because to grep the file is a pipe and stdin.

>JRF: echo "[ $F ]"

The problem with this is that it always produces output whether there is a match. Most times when I'm lazy, I do the same thing. Especially if you use: echo "Doing $F =======",
so you can see the names and the strings.

If I want something foolproof, you need something like Kaps01's, where it echos only if it finds it.
Hemmetter
Esteemed Contributor

Re: grep to show filename

Hi Dave,

What about:
$ grep -l mystring *.xxx


rgds
HGH
Dennis Handly
Acclaimed Contributor

Re: grep to show filename

>HGH: What about: $ grep -l mystring *.xxx

Dave said they were binary files and that's why strings -a was used.
James R. Ferguson
Acclaimed Contributor
Solution

Re: grep to show filename

Hi (again) Dave:

OK, here's a way to avoid temporary files, superfluous output, and multiple processes:

By example, suppose you wanted to find "UNIX" in several binary files. You can do:

# perl -nle 'BEGIN{use open IO=>":raw"};while (/([\040-\176\s]{4,})/g) {$p=$1;print $ARGV,":",$p if $p=~/UNIX/}' /usr/bin/date /usr/bin/cp /usr/bin/mv

/usr/bin/date:UNIX95
/usr/bin/cp:UNIX95
/usr/bin/cp:UNIX95
/usr/bin/mv:UNIX95

This Perl script emulates 'strings'. Change the pattern to match whatever you want. Pass one or more filesnames or let the shell expand a glob like "*.xxx" instead. You can add 'i' for case-insensitive matches if you want. Thus, to find the pattern "mystring" case-insensitively, change:

$p=~/UNIX/}

to:

$p=~/mystring/i}

Regards!

...JRF...