简体   繁体   中英

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

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.

One needs to turn on extended glob functionality of bash to be able to use the advanced pattern matching.

$ 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] ; 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 .

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.

You could pipe the output from ls into grep. Grep has an "invert" option (to show lines that don't match), so you could do this:

 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.

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 :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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