仅在 Bash 中搜索文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20745656/
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 09:04:45  来源:igfitidea点击:

Globbing for only files in Bash

bashglob

提问by John P

I'm having a bit of trouble with globs in Bash. For example:

我在 Bash 中遇到了一些问题。例如:

echo *

This prints out all of the files and folders in the current directory. e.g. (file1 file2 folder1 folder2)

这将打印出当前目录中的所有文件和文件夹。例如(文件 1 文件 2 文件夹 1 文件夹 2)

echo */

This prints out all of the folders with a / after the name. e.g. (folder1/ folder2/)

这将打印出名称后带有 / 的所有文件夹。例如(文件夹 1/ 文件夹 2/)

How can I glob for just the files? e.g. (file1 file2)

我怎样才能只搜索文件?例如(文件 1 文件 2)

I know it could be done by parsing ls but also know that it is a bad idea. I tried using extended blobbing but couldn't get that to work either.

我知道这可以通过解析 ls 来完成,但也知道这是一个坏主意。我尝试使用扩展 blobing,但也无法使其正常工作。

回答by anubhava

WIthout using any external utility you can try for loopwith glob support:

无需使用任何外部实用程序,您可以尝试for loop使用glob support

for i in *; do [ -f "$i" ] && echo "$i"; done

回答by Oliver Charlesworth

I don't know if you can solve this with globbing, but you can certainly solve it with find:

我不知道你是否可以用 globbing 来解决这个问题,但你当然可以用find来解决它:

find . -type f -maxdepth 1

回答by Major Gnuisance

You can do what you want in bash like this:

你可以像这样在 bash 中做你想做的事:

shopt extglob
echo !(*/)

But note that what this actually does is match "not directory-likes."
It will still match dangling symlinks, symlinks pointing to not-directories, device nodes, fifos, etc.

但请注意,这实际上是匹配“非目录类”。
它仍然会匹配悬空符号链接、指向非目录的符号链接、设备节点、fifos 等。

It won't match symlinks pointing to directories, though.

但是,它不会匹配指向目录的符号链接。

If you want to iterate over normal files and nothing more, use find -maxdepth 1 -type f.

如果您只想遍历普通文件,仅此而已,请使用find -maxdepth 1 -type f.

The safe and robust way to use it goes like this:

使用它的安全和健壮的方式是这样的:

find -maxdepth 1 -type f -print0 | while read -d $'##代码##' file; do
  printf "%s\n" "$file"
done