Linux下查找当前目录下所有包含某个字符串的文件

2018-5-18

操作系统:debian 7

Python版本:3.5.3

注意:请不要输入双引号,如果硬是要输入,请在双引号前加转义符”  \ “,其它特殊字符类似处理


2019-5-31更新,重新编写在python2下的代码


2018-5-26更新,路径中也不能有空格


为什么为想到写这样一个简单的程序呢,因为WordPress里面有太多函数,如果我们知道了网页某个地方的class属性(谷歌浏览器,F12键打开开发者模式),我们就可以去修改源代码,而我们并不知道究竟是那个源文件,这时这个小程序就起作用了。

Python版本大于3应该都可以,代码中由于有中文,在Python2中会报错。只适用与Linux,因为里面用到“ grep ”这个命令。

要查找多种文件类型的文件是否含有某一字符串,多次执行,并修改一下后缀即可。并不复杂。

如果字符串中含有空格的,请用“ \ ”代替,如需搜索 Free energy 输入字符时请这样输入“ Free\ energy ”

#look the strings in the current dir file (such as php html)
#查考当前目录及子目录下文本文件含有某个字符串的文件,只能在Linux上使用,因为使用到了Linux的命令
import os
string0=input('请输入需要查找的字符:')
string1=input('请输入需要查到的文件类型(用后缀名区分,空代表所有):')
while(len(string0)==0): #避免用户没有输入
    string0=input('please input what you are looking for:')
CurrentPath=os.getcwd()
for root,dirs,files in os.walk(CurrentPath): #一次一次的判断
    for file in files:
        file=os.path.join(root,file) #获得文件的绝对路径
        if file.endswith('%s'%string1): #看文件是否以string1结尾
            result=os.system('cat %s | grep %s --color=auto'%(file,string0)) #查找文件是否含有string0
            if(result==0): #实测,当查询到东西时,result=0,没查到时为255
                print('-'*80)
                print(file+' 含有搜索的字符 '+'%s'%string0)
                print('-'*80)


#number=os.walk(CurrentPath,topdown=True,onerror=None,followlinks=False)
#for (root,dirs,files) in number:
# print(root) #返回目录的路径
# print(files) #返回所有子目录
# print(dirs) #返回所有文件 ,不含路径信息

2019-5-31更新,python2版本,不支持中文

import os
string0=raw_input('Please input what do you want to find :')
string1=raw_input('file type:(suffix,empty represent all):')
while(len(string0)==0):
    string0=raw_input('please input what you are looking for:')
CurrentPath=os.getcwd()
for root,dirs,files in os.walk(CurrentPath):
    for file in files:
        file=os.path.join(root,file)
        if file.endswith('%s'%string1):
            result=os.system('cat %s | grep %s --color=auto'%(file,string0))
            if(result==0):
                print('-'*80)
                print(file+' include the char '+'%s'%string0)
                print('-'*80)

几乎一瞬间就查到了,简直是美滋滋

源码下载

欢迎转载,不需注明出处,就说是你写的

Subscribe
提醒
guest
0 评论
内联反馈
查看所有评论