Regex 我如何使用tcl搜索文件,而只使用部分文件名
如果我有一个包含以下文件的文件夹:Regex 我如何使用tcl搜索文件,而只使用部分文件名,regex,bash,foreach,tcl,ls,Regex,Bash,Foreach,Tcl,Ls,如果我有一个包含以下文件的文件夹: hello-version-1-090.txt hello-awesome-well-091.txt goodday-087.txt hellooo-874.txt hello_476.txt hello_094.txt 如何使用tcl搜索其中包含“hello”和“091”的文件 可能的解决办法: 在文件夹中获取ls-l的输出,用'\n'将其拆分,然后在每行上运行foreach,并使用regexp匹配条件。但是如何在文件夹中运行ls-l,并使用tcl记录其内
hello-version-1-090.txt
hello-awesome-well-091.txt
goodday-087.txt
hellooo-874.txt
hello_476.txt
hello_094.txt
如何使用tcl搜索其中包含“hello”和“091”的文件
可能的解决办法:
在文件夹中获取
ls-l
的输出,用'\n'
将其拆分,然后在每行上运行foreach
,并使用regexp匹配条件。但是如何在文件夹中运行ls-l
,并使用tcl记录其内容(文件名) 使用glob
,您可以应用该模式并获得符合我们标准的文件名列表
puts [ exec ls -l ]; #Just printing the 'ls -l' output
set myfiles [ glob -nocomplain hello*091*.txt ]
if {[llength $myfiles]!=0} {
puts "Following files matched your pattern : "
foreach fname $myfiles {
puts $fname
}
} else {
puts "No files matched your pattern"
}
使用-nocomplain
的原因是,如果没有与我们的搜索模式匹配的文件,则允许返回空列表而不会出错
输出
sh-4.2# tclsh main.tcl
total 4
-rw-r--r-- 1 root root 0 Mar 4 15:23 goodday-087.txt
-rw-r--r-- 1 root root 0 Mar 4 15:23 hello-awesome-well-091.txt
-rw-r--r-- 1 root root 0 Mar 4 15:23 hello-version-1-090.txt
-rw-r--r-- 1 root root 0 Mar 4 15:23 hello_094.txt
-rw-r--r-- 1 root root 0 Mar 4 15:23 hello_476.txt
-rw-r--r-- 1 root root 0 Mar 4 15:23 hellooo-874.txt
-rw-r--r-- 1 root root 262 Mar 4 15:24 main.tcl
Following files matched your pattern :
hello-awesome-well-091.txt
顺便说一下,关于如何保存ls-l
输出的查询,只需将输出保存到变量中即可
set result [ exec ls -l ]
然后使用result
变量,您可以通过逐行循环的方式应用regexp
,正如您所提到的
但是,我希望使用glob
将是一种更好的方法
参考资料:使用
glob
,您可以应用该模式并获得符合我们标准的文件名列表
puts [ exec ls -l ]; #Just printing the 'ls -l' output
set myfiles [ glob -nocomplain hello*091*.txt ]
if {[llength $myfiles]!=0} {
puts "Following files matched your pattern : "
foreach fname $myfiles {
puts $fname
}
} else {
puts "No files matched your pattern"
}
使用-nocomplain
的原因是,如果没有与我们的搜索模式匹配的文件,则允许返回空列表而不会出错
输出
sh-4.2# tclsh main.tcl
total 4
-rw-r--r-- 1 root root 0 Mar 4 15:23 goodday-087.txt
-rw-r--r-- 1 root root 0 Mar 4 15:23 hello-awesome-well-091.txt
-rw-r--r-- 1 root root 0 Mar 4 15:23 hello-version-1-090.txt
-rw-r--r-- 1 root root 0 Mar 4 15:23 hello_094.txt
-rw-r--r-- 1 root root 0 Mar 4 15:23 hello_476.txt
-rw-r--r-- 1 root root 0 Mar 4 15:23 hellooo-874.txt
-rw-r--r-- 1 root root 262 Mar 4 15:24 main.tcl
Following files matched your pattern :
hello-awesome-well-091.txt
顺便说一下,关于如何保存ls-l
输出的查询,只需将输出保存到变量中即可
set result [ exec ls -l ]
然后使用result
变量,您可以通过逐行循环的方式应用regexp
,正如您所提到的
但是,我希望使用glob
将是一种更好的方法
参考资料:您甚至可以使用
glob
命令递归地扫描一个目录和所有对您可能有用的子目录。我想看看这些文档,你甚至可以用glob
命令递归地扫描一个目录和所有对你有用的子目录。我想看一下文档。Glob方法更加优雅,非常感谢!!Glob方法更加优雅,非常感谢!!