shell - python实现把多级目录多个JS文件中包含某字符的字符串提取出来并加上标示存入一个文本文件中。

查看:122
本文介绍了shell - python实现把多级目录多个JS文件中包含某字符的字符串提取出来并加上标示存入一个文本文件中。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

一个草图:

现实现在文件夹和子文件夹下查找目标字符串,
但不知如何提取包含目标字符的字符串,并写入到新文件中。

#!/usr/bin/env python
#-*- coding:utf-8 -*-
import os, sys
import fnmatch

listonly = False
skipexts = ['.js']
def visitfile(fname,searchkey):
    global fcount,vcount
    try:
        if not listonly:
            if os.path.splitext(fname)[1] in skipexts:
                if open(fname).read().find(searchkey) != -1:
                    print '%s has %s '%(fname,searchkey)
                    fcount+=1
    except: pass
    vcount +=1

def visitor(args,directoryName,filesInDirectory):
    for fname in filesInDirectory:
        # 返回文件所在路径和文件名
        fpath = os.path.join(directoryName,fname)
        if not os.path.isdir(fpath):

            visitfile(fpath,args)

def searcher(startdir,searchkey):
    global fcount,vcount
    fcount = vcount = 0
    os.path.walk(startdir,visitor,searchkey)

if __name__=='__main__':
    # root=raw_input("type root directory:")
    root = '/home/jiangbin/findJS'
    key=raw_input("type key:")
    searcher(root,key)
    print 'Found in %d files,visited %d'%(fcount,vcount)

run

type key:JSQ
/home/jiangbin/findJS/XXX.js has JSQ 
/home/jiangbin/findJS/JSQ.js has JSQ 
Found in 2 files,visited 19

解决方案

你不是完成得差不多了嘛....

https://gist.github.com/wusisu/e08ee53513c4410cf9ddd1ba5b0b80f5
我帮你完成了

----但是实际上,用shell就ok了--------

find . -type f -name "*.js" | xargs grep work_to_be_searched

find . -type f -name "*.js" | xargs grep work_to_be_searched > out.txt

  • 这里 find 的 type f 表示只显示文件 name 就是以 .js 结尾

  • 通过 xargs 传递

  • 用 grep 来搜索关键词

  • 最后用 > 导出

这篇关于shell - python实现把多级目录多个JS文件中包含某字符的字符串提取出来并加上标示存入一个文本文件中。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆