简体   繁体   English

在 ls (bash) 中匹配文件名

[英]Matching filename in ls (bash)

I have the following files我有以下文件

tcpdump-12
tcpdump-12.delay
tcpdump-24
tcpdump-24.delay

Is there a way to ls only the files有没有办法只ls文件

tcpdump-12
tcpdump-24

I can do我可以

ls tcpdump-[[:digit:]][[:digit:]]

but I am looking for something more generic that can take any number of digits, something like tcpdump-[0-9]+ if I was using vim or python regular expressions.但我正在寻找可以采用任意数字的更通用的东西,比如 tcpdump-[0-9]+ 如果我使用 vim 或 python 正则表达式。

One needs to turn on extended glob functionality of bash to be able to use the advanced pattern matching. 需要启用bash的扩展glob功能才能使用高级模式匹配。

$ ls
tcpdump-12  tcpdump-12.delay  tcpdump-24  tcpdump-24.delay
$ shopt -s extglob
$ ls tcpdump-+([[:digit:]])
tcpdump-12  tcpdump-24

如果您确定所有不需要的文件以“.delay”结尾,则可以执行以下操作:

 ls --ignore '*.delay' 

I'm not sure why you're using [[:digit:]] rather than [0-9] ; 我不确定你为什么使用[[:digit:]]而不是[0-9] ; are you concerted the file names might contain other kinds of digits? 你是否齐心协力,文件名可能包含其他类型的数字?

Most of the other answers are good, but a quick-and-dirty solution is: 大多数其他答案都很好,但一个快速而肮脏的解决方案是:

ls tcpdump-*[0-9]

It works for the particular set of files you have, but it would also match file names like tcpdump-FOO7 . 它适用于您拥有的特定文件集,但它也会匹配文件名,如tcpdump-FOO7

In a general-purpose script, it's worth the effort to match exactly the pattern you want. 在通用脚本中,值得精确匹配您想要的模式。 In a one-short interactive shell command, sloppy shortcuts that just happen to work for the current situation can be useful. 在一个简短的交互式shell命令中,恰好适用于当前情况的草率快捷方式可能很有用。

You could pipe the output from ls into grep. 您可以将ls的输出传输到grep中。 Grep has an "invert" option (to show lines that don't match), so you could do this: Grep有一个“反转”选项(显示不匹配的行),所以你可以这样做:

 ls tcpdump-* | grep -v '\.delay$'

If you don't mind passing them through an external filter, you can use: 如果您不介意通过外部过滤器传递它们,您可以使用:

ls -1 tcpdump-* | grep '^tcpdump-[0-9]*$'

Just keep in mind this ends up giving you one per line rather than a nice multi-columnar ls output. 请记住,这最终会给你一条线而不是一个漂亮的多柱状ls输出。

If you're processing that list, it wont matter too much but, if you just want to see those files in a directory listing, it's not good enough. 如果您正在处理该列表,那就不会太重要,但是,如果您只是想在目录列表中看到这些文件,那就不够好了。 I'm assuming the former since, otherwise, this question doesn't really belong on SO :-) 我假设前者,否则,这个问题并不属于SO :-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM