首页 > 解决方案 > 仅列出仅包含一个特定字符的文件,当未指定重复数量时

问题描述

如何在不知道文件名长度的情况下简单地列出包含一个特定字符的所有文件。例如,如果我有名称从 test0 开始并以 test10000 结尾的文件,并且我想列出所有仅包含数字 9 的文件。结果应该是 test9、test99、test999、test9999。

目前我的代码看起来像这样 ls test{9,99,999,9999},非常静态,我正在寻找更动态的代码。

标签: linuxbash

解决方案


一种解决方案使用ls

$ ls -1
file.ycz.99.88.txt                 # not a match
file.ycz.99.txt                    # match
file09.txt                         # not a match
file9.txt                          # match
file993.txt                        # not a match

$ ls -1I "*[0-8]*"                 # '-I' says to ignore files that match the pattern
file.ycz.99.txt
file9.txt

注意:我添加了“-1”以将每个文件放在单独的行上,仅出于本答案的可读性目的


为了让它更有活力,虽然有点冗长:

$ ignore='[0123456789]'
$ keep='9'
$ ls -1I "*${ignore//${keep}}*"     # '${ignore//${keep}}' strip '9' from the 'ignore' variable leaving us with 'ls "*[012345678]*"
file.ycz.99.txt
file9.txt

要查看正在运行的扩展:

$ set -xv
$ ls -1I "*${ignore//${keep}}*"
+ ls -1I '*[012345678]*'
file.ycz.99.txt
file9.txt

推荐阅读