bash - 是否可以列出与 ls 模式匹配的文件?

标签 bash shell file sh ls

我想在不使用 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

但它不起作用! :/

最佳答案

仅适用于 lsls 根本不知道模式。它只能与 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/

相关文章:

python - 如何在 bash 中自动完成我的 python 函数?

python - 无法使用 `azcopy login --tenant-id` 和 Azure 政府帐户的租户 ID 登录 Azure?

bash - 在 Ubuntu 中转换音频文件的采样率的脚本

linux - 在 shell 脚本中更改 shell

java - 将字节数组写入java中的子文件夹

macos - 使用 OpenSSL 和 OAuth2 从命令行访问 IMAP 服务器

庆典 printf : How do I output\x and\f within double quotes?

arrays - 将值添加到以变量命名的关联数组

cocoa-touch - 使用 NSFileWrapper 写入与使用 NSFileManager 复制

Python:具有实际磁盘文件语义的命名内存文件?