Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search directory for specific string

I'm trying to search through a specific directory full of header files, and look through each header file, and if any file has a string "struct" in it, I just want the program to print which file has it.

I have this so far, but it's not working correctly, can you help me figure it out:

import glob
import os
os.chdir( "C:/headers" )
for files in glob.glob( "*.h" ):
    f = open( files, 'r' )
    for line in f:
        if "struct" in line:
            print( f )
like image 723
chakolatemilk Avatar asked Feb 05 '13 15:02

chakolatemilk


People also ask

How do I search for a string in a directory?

If you'd like to always search within file contents for a specific folder, navigate to that folder in File Explorer and open the “Folder and Search Options.” On the “Search” tab, select the “Always search file names and contents” option.

How do I find a specific string in a directory in Linux?

Grep is a Linux / Unix command-line tool used to search for a string of characters in a specified file. The text search pattern is called a regular expression. When it finds a match, it prints the line with the result. The grep command is handy when searching through large log files.

How do I find all files containing specific text?

Without a doubt, grep is the best command to search a file (or files) for a specific text. By default, it returns all the lines of a file that contain a certain string. This behavior can be changed with the -l option, which instructs grep to only return the file names that contain the specified text.


1 Answers

It seems you are interested in the file name, not the line, so we can speed thing up by reading the whole file and search:

...
for file in glob.glob('*.h'):
    with open(file) as f:
        contents = f.read()
    if 'struct' in contents:
        print file

Using the with construct ensures the file to be closed properly. The f.read() function reads the whole file.

Update

Since the original poster stated that his code was not printing, I suggest to insert a debugging line:

...
for file in glob.glob('*.h'):
    print 'DEBUG: file=>{0}<'.format(file)
    with open(file) as f:
        contents = f.read()
    if 'struct' in contents:
        print file

If you don't see any line that starts with 'DEBUG:', then your glob() returned an empty list. That means you landed in a wrong directory. Check the spelling for your directory, along with the directory's contents.

If you see the 'DEBUG:' lines, but don't see the intended output, your files might not have any 'struct' in in. Check for that case by first cd to the directory, and issue the following DOS command:

find "struct" *.h
like image 78
Hai Vu Avatar answered Sep 29 '22 09:09

Hai Vu