File Glob Patterns in Linux terminal

2019-03-01 13:51发布

I want to search a filename which may contain kavi or kabhi. I wrote command in the terminal:

ls -l *ka[vbh]i*

Between ka and i there may be v or bh .

The code I wrote isn't correct. What would be the correct command?

标签: linux glob
3条回答
SAY GOODBYE
2楼-- · 2019-03-01 14:03

A nice way to do this is to use extended globs. With them, you can perform regular expressions on Bash.

To start you have to enable the extglob feature, since it is disabled by default:

shopt -s extglob

Then, write a regex with the required condition: stuff + ka + either v or bh + i + stuff. All together:

ls -l *ka@(v|bh)i*

The syntax is a bit different from the normal regular expressions, so you need to read in Extended Globs that...

@(list): Matches one of the given patterns.

Test

$ ls
a.php  AABB  AAkabhiBB  AAkabiBB  AAkaviBB  s.sh
$ ls *ka@(v|bh)i*
AAkabhiBB  AAkaviBB
查看更多
萌系小妹纸
3楼-- · 2019-03-01 14:07

You can get what you want by using curly braces in bash:

ls -l *ka{v,bh}i*

Note: this is not a regular expression question so much as a "shell globbing" question. Shell "glob patterns" are different from regular expressions, though they are similar in many ways.

查看更多
倾城 Initia
4楼-- · 2019-03-01 14:10

a slightly longer cmd line could be using find, grep and xargs. it has the advantage of being easily extended to different search terms (by either extending the grep statement or by using additional options of find), a bit more readability (imho) and flexibility in being able to execute specific commands on the files which are found

find . | grep -e "kabhi"  -e "kavi" | xargs ls -l
查看更多
登录 后发表回答