我想在不使用 grep
的情况下使用 ls
列出与模式匹配的目录文件。可能吗?
重点是检索所有匹配此模式的文件 '^\Extra_text_[0-9]\{10\}.csv'
数一数我得到了多少。
我试过这段代码:
ls | grep '^\Extra_text_[0-9]\{10\}.csv'
InputName=' | grep ^\Extra_text_[0-9]\{10\}.csv'
fileCount=`ls $INPUT_FILE/$InputName 2>/dev/null | wc -l`
echo "$fileCount
但它不起作用! :/
最佳答案
仅适用于 ls
。 ls
根本不知道模式。它只能与 shell 提供的通配符(通配符 *
和 ?
或扩展的通配符 - 请参阅 Bash 手册页中的 extglob
一起使用,但不适用于正则表达式。
一个简单的方法是使用 find
来完成这项工作(注意正则表达式需要匹配整个文件名):
find . -regex '<yourpattern>'
要计算结果,通过管道传输到 wc
:
# safe for corner case: version of find w/o newline escaping and files with newlines:
find . -regex '<yourpattern>' -printf '.' | wc -c
# fallback for non-GNU platform, corner cases not addressed:
find . -regex '<yourpattern>' | wc -l
在 find
手册页中查找 -regex
以获取更多信息。
关于bash - 是否可以列出与 ls 模式匹配的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56259774/