四月 9th, 2010
shell 小工具:ytgrep(查询包含指定字符的所有文件)
由于有个小需求如本文标题,实在是因为本人shell命令熟知的不多,google了几下,没g出来,因此才产生了这个东西。
ytgrep实现很简单,代码也不是很好,不过俺还是贴在博客上。
[root@web-node20 ~]# ytgrep -h ytgrep -v1.0 Author: xiongyq (I work in yite), E-mail: xyqfans@gmail.com This is free software, and you are welcome to modify. -d [directory/file] 指定要查询的目录,默认是当前目录。 -r 是否递归遍历所有目录下的文件,默认是只查询当前目录不遍历子目录。 -q [str] 查询的字符串 -v 树状显示目录文件结构,代码摘自 LINUX的C编程。 -h help?
[root@web-node20 log]# ytgrep -d kestrel/ -q "kestrel" /var/log/kestrel/kestrel-20100330.log /var/log/kestrel/kestrel-20100401.log /var/log/kestrel/kestrel.log [root@web-node20 log]# ytgrep -d kestrel/ -v kestrel-20100330.log kestrel-20100401.log kestrel.log kestrel/ temp/ error.log k2.log k3.log k1.log [root@web-node20 log]#
这里是一个递归函数:
void print_dir(char *dir, int depth) { DIR *dp; struct dirent *entry; struct stat statbuf; if ((dp = opendir(dir)) == NULL) { fprintf(stderr, "cannot open directory: %sn", dir); return; } chdir(dir); while ((entry = readdir(dp)) != NULL) { lstat(entry->d_name, &statbuf); if (S_ISDIR(statbuf.st_mode)) { if (strcmp(".", entry->d_name) == 0 || strcmp("..", entry->d_name) == 0) continue; printf("%*s%s/n", depth, "", entry->d_name); print_dir(entry->d_name, depth + 4); } else printf("%*s%sn", depth, "", entry->d_name); } chdir(".."); closedir(dp); }
source:get
wget http://www.ys250.com/download/ytgrep.tar.gz

五月 29th, 2010 1:24 下午
ytgrep这个东西,用c是不是太大头了,你用py完全可以搞定的。何必呢。