如何使用 bash 或 Perl 脚本遍历目录树?
我对 bash 脚本很感兴趣,并且想知道如何遍历 unix 目录并记录当前正在查看的文件的路径(如果它与正则表达式条件匹配)。
它会像这样:
- 遍历一个大的unix目录路径文件/文件夹结构。
- 如果当前文件的内容包含与一个或多个正则表达式匹配的字符串,
- 则将文件的完整路径附加到结果文本文件。
Bash 或 Perl 脚本都可以,但我更喜欢使用带有 grep、awk 等命令的 bash 脚本来执行此操作。
I am interested into getting into bash scripting and would like to know how you can traverse a unix directory and log the path to the file you are currently looking at if it matches a regex criteria.
It would go like this:
- Traverse a large unix directory path file/folder structure.
- If the current file's contents contained a string that matched one or more regex expressions,
- Then append the file's full path to a results text file.
Bash or Perl scripts are fine, although I would prefer how you would do this using a bash script with grep, awk, etc commands.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
重要部分:
使用 xargs 的一个很酷的事情是,如果您的目录确实包含很多文件,您可以通过并行来加速该过程it:
这将在 5 个单独的副本中运行 grep 命令,每个副本扫描另一组最多 100 个文件
Important parts:
The cool thing with using xargs is, that if your directory contains really a lot of files, you can speed up the process by paralleling it:
This will run the grep command in 5 separate copies, each scanning another set of up to 100 files
使用 find 和 grep
-l
在 grep 上仅获取文件名-e
在 grep 上指定一个正则表达式{}
将找到的每个文件放置在grep 命令末尾的 find 命令>> outfile.txt
附加到文本文件use find and grep
-l
on the grep gets just the file name-e
on the grep specifies a regex{}
places each file found by the find command on the end of the grep command>> outfile.txt
appends to the text filegrep -l -R <正则表达式>应该可以完成这项工作。
grep -l -R <regex> <location>
should do the job.,您可以采用人们建议的
find
命令,并使用find2perl
将它们转换为 Perl 脚本:如果您有:
如果您想在 Perl 中执行此
操作 输出一个执行相同操作的 Perl 程序。 从那时起,如果您需要在 Perl 中做一些简单但在 shell 中却很难的事情,您只需扩展 Perl 程序即可。
If you wanted to do this from within Perl, you can take the
find
commands that people suggested and turn them into a Perl script withfind2perl
:If you have:
make that
That outputs a Perl program that does the same thing. From there, if you need to do something that easy in Perl but hard in shell, you just extend the Perl program.
类似线程
similar thread