Case-insensitive Glob on zsh/bash

≯℡__Kan透↙ 提交于 2019-11-27 17:06:34

问题


I need to list all files whose names start with 'SomeLongString'. But the case of 'SomeLongString' can vary. How?

I am using zsh, but a bash solution is also welcome.


回答1:


ZSH:

$ unsetopt CASE_GLOB

Or, if you don't want to enable case-insensitive globbing in general, you can activate it for only the varying part:

$ print -l (#i)(somelongstring)*

This will match any file that starts with "somelongstring" (in any combination of lower/upper case). The case-insensitive flag applies for everything between the parentheses and can be used multiple times. Read the manual zshexpn(1) for more information.

UPDATE Almost forgot, you have to enable extendend globbing for this to work:

setopt extendedglob



回答2:


bash:

shopt -s nocaseglob



回答3:


Depending on how deep you want to have this listing, find offers quite a lot in this regard:

find . -iname 'SomeLongString*' -maxdepth 1

This will only give you the files in the current directory. Important here is the -iname parameter instead of -name.




回答4:



$ function i () {
> shopt -s nocaseglob; $*; shopt -u nocaseglob
> }
$ ls *jtweet*
ls: cannot access *jtweet*: No such file or directory
$ i ls *jtweet*
JTweet.pm  JTweet.pm~  JTweet2.pm  JTweet2.pm~



回答5:


For completeness (and frankly surprised it's not mentioned yet, even though all the other answers are better and/or "more correct"), obviously one can also use (especially for grep aficionados):

$ ls | egrep -i '^SomeLongString'

One might also stick in a redundant ls -1 (that's option "one", not "ell"), but when passed to a pipe, each entry is already going to be one per line, anyway. I'd typically use something like this (vs set) in shell scripts, eg in a for/while loop: for i in $(ls | grep -i ...) . However, the other answer using find would be preferable & more flexible in that circumstance, because you can, for example, omit directories (or set other restrictions): for i in $(find . -type f -iname 'SomeString*' -print -maxdepth 1)... or even forgo the loop altogether and just use the power of find all by itself, eg: find ... -exec do_stuff {} \; ... , but I do digress (again, for completeness.)



来源:https://stackoverflow.com/questions/156916/case-insensitive-glob-on-zsh-bash

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!