Bash List文件与模式数组不匹配

时间:2017-03-10 11:07:40

标签: bash pattern-matching

我对bash没有经验,我有一个问题。

我正在尝试选择一些与某个阵列模式不匹配的文件(让我们说这个例子是ls)。

我有两个名为Test,Test1,Test2,Test3,Test4,Test5,Test6,Test7,Test8,Test9,Test10的文件,我需要在两组中选择。

第一组是Test5,Test6,Test7,Test8,Test9,Test10,我可以使用以下列出:

ls -l T*@(5|6|7|8|9|10) or ls -l T*{5,6,7,8,9,10}

第二组是一个棘手的(对我来说)因为测试& Test1文件。我试图反转以前的选择/列表..或以某种方式选择其余的。 我尝试了几件没有运气的事情:

ls -l T*[!5678910]
ls -l T*[!@(5|6|7|8|9|10)]
ls -l T*[!5][!6][!7][!8][!9][!10]
ls -l T*@(1|2|3|4|)

p.s:实际的文件名在数字后面有额外的字符。

4 个答案:

答案 0 :(得分:8)

您可以反转这样的模式:

# enable extended glob, if disabled, it will not function
shopt -s extglob

# create our files
touch {Test,Test1,Test2,Test3,Test4,Test5,Test6,Test7,Test8,Test9,Test10}

# list files with matching pattern
ls -1 T*@(5|6|7|8|9|10)
Test10
Test5
Test6
Test7
Test8
Test9


# list files with NOT matching pattern
ls -1 T!(*@(5|6|7|8|9|10))
Test
Test1
Test2
Test3
Test4

答案 1 :(得分:2)

您可以在列表中使用空字符串作为选项:

ls -l Test*{,1,2,3,4}

[编辑]但总的来说,我没有看到单独使用bash进行倒置匹配的方法。我现在也看到数字后面可能还有其他字符(我想非数字,或者你无法区分)。我会用'grep',可能用'-v'标志来否定。

ls -1 |  grep -v "Test\(\(5\)\|\(6\)\|\(7\)\|\(8\)\\|\(9\)\|\(10\)\)"

答案 2 :(得分:1)

我不确定为什么它不能与*一起使用,但它适用于更具体的模式:

ls -l Test@(1|2|3|4|)
ls -l Test?([1-4])
ls -l T+([^0-9])?([1-4])

答案 3 :(得分:1)

如果ls不是您唯一可接受的命令,您也可以find使用regex来实现您的目的:

  • 创建所有测试文件:

    touch Test{,1,2,3,4,5,6,7,8,9,10}

  • 使用regex找到第一组文件:

    find -type f -regex "\./Test\([5-9]\|10\)"

  • 反向很简单,只需在选项!之前添加-regex

    find -type f ! -regex "\./Test\([5-9]\|10\)"

适用于Linux Bash。