[英]How can I traverse a directory tree using a bash or Perl script?
我有兴趣进入bash脚本,并想知道如何遍历unix目录并记录当前正在查看的文件的路径,如果它符合正则表达式标准。
它会是这样的:
Bash或Perl脚本很好,虽然我更喜欢你如何使用带有grep , awk等命令的bash脚本来实现这一点。
find . -type f -print0 | xargs -0 grep -l -E 'some_regexp' > /tmp/list.of.files
重要部分:
使用xargs的好处是,如果你的目录包含很多文件,你可以通过并行来加速这个过程:
find . -type f -print0 | xargs -0 -P 5 -L 100 grep -l -E 'some_regexp' > /tmp/list.of.files
这将以5个单独的副本运行grep命令,每个副本扫描另一组最多100个文件
使用find和grep
find . -exec grep -l -e 'myregex' {} \; >> outfile.txt
grep上的-l
只获取文件名
-e
on the grep指定正则表达式
{}
将find命令找到的每个文件放在grep命令的末尾
>> outfile.txt
附加到文本文件
grep -l -R <regex> <location>
应该完成这项工作。
如果你想在Perl中执行此操作,可以使用人们建议的find
命令并将它们转换为带有find2perl
的Perl脚本:
如果你有:
$ find ...
做那个
$ find2perl ...
这会输出一个执行相同操作的Perl程序。 从那里开始,如果你需要在Perl中做一些简单但在shell中很难的东西,你只需要扩展Perl程序。
find /path -type f -name "*.txt" | awk '
{
while((getline line<$0)>0){
if(line ~ /pattern/){
print $0":"line
#do some other things here
}
}
}'
类似的线程
find /path -type f -name "outfile.txt" | awk '
{
while((getline line<$0)>0){
if(line ~ /pattern/){
print $0":"line
}
}
}'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.