Bash ls(全局样式)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14068868/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 04:06:13  来源:igfitidea点击:

Bash ls (glob-style)

linuxbashunixls

提问by user1923376

I have an excersise in which I have to print all the file names which are contained in the current folder, which contain in the them one of the letters [a-k]and [m-p]and [1-9]atleast 1 time (each). I probably have to use ls(glob-style).

我有,我有打印所有这些都包含在当前文件夹中的文件名,其中包含在字母的其中之一的excersise[a-k][m-p][1-9]ATLEAST 1次(每次)。我可能不得不使用ls(glob-style)

回答by Chris Seymour

If order is important then you can use globbing:

如果顺序很重要,那么您可以使用通配符:

$ ls *[a-k]*[m-p]*[1-9]*
ajunk404  am1  cn5

Else just grepfor each group separately:

否则仅grep针对每个组分别:

ls | grep "[a-k]" | grep "[m-p]" | grep "[1-9]"
1ma
ajunk404
am1
cn5
m1a

Note: lswill show directories if you really only want files use findinside:

注意:ls如果您真的只想find在内部使用文件,则会显示目录:

find . -maxdepth 1 -type f | grep "[a-k]" | grep "[m-p]" | grep "[1-9]"

回答by gniourf_gniourf

A 100% pure bash (and funny!) possibility:

100% 纯 bash(而且很有趣!)的可能性:

#!/bin/bash

shopt -s nullglob
a=( *[a-k]* )
b=(); for i in "${a[@]}"; do [[ "$i" = *[p-z]* ]] && b+=( "$i" ); done
c=(); for i in "${b[@]}"; do [[ "$i" = *[1-9]* ]] && c+=( "$i" ); done
printf "%s\n" "${c[@]}"

No external processes whatsoever! No pipes! Only pure bash! 100% safe regarding files with funny symbols in their name (e.g., newlines) (and that's not the case with other methods using ls). And if you want to actually see the funny symbols in the file names and have them properly quoted, so as to reuse the output, use

没有任何外部过程!没有管道!只有纯粹的bash!对于名称中带有有趣符号的文件(例如换行符),100% 安全(使用 的其他方法并非如此ls)。如果您想真正看到文件名中的有趣符号并正确引用它们,以便重用输出,请使用

printf "%q\n" "${c[@]}"

in place of the last printfstatement.

代替最后printf一句。

Note.The patterns [a-k], [p-z]are locale-dependent. You might want to set LC_ALL=Cto be sure that [a-k]really means [abcdefghijk]and not something else, e.g., [aAbBcCdDeEfFgGhHiIjJk].

笔记。模式[a-k],[p-z]是语言环境相关的。您可能想要设置LC_ALL=C以确保它[a-k]真正意味着[abcdefghijk]而不是其他东西,例如,[aAbBcCdDeEfFgGhHiIjJk]

Hope this helps!

希望这可以帮助!

回答by glenn Hymanman

To be complete, you need to search all the combinations:

要完成,您需要搜索所有组合:

ls *[a-k]*[m-p]*[1-9]* *[a-k]*[1-9]*[m-p]* \
   *[m-p]*[a-k]*[1-9]* *[m-p]*[1-9]*[a-k]* \
   *[1-9]*[m-p]*[a-k]* *[1-9]*[a-k]*[m-p]*

回答by cmh

If order isn't important, and the letters appear once or more, you can use chained greps.

如果顺序不重要,并且字母出现一次或多次,则可以使用链式 grep。

ls | egrep "[a-k]" | egrep "[m-p]" | egrep "[1-9]"

If order matters, then just use a glob pattern

如果顺序很重要,那么只需使用 glob 模式

ls *[a-k]*[m-p]*[1-9]*