简体   繁体   English

Bash:使用通配符区分文件和目录

[英]Bash: Differentiate between files and directories with wildcards

I have a couple of files in my working directory and I want to print all of the textual files, the problem is in my WD are also directories. 我的工作目录中有几个文件,我想打印所有文本文件,问题出在我的WD也是目录中。 This means, when I type: 这意味着,当我键入:

cat *

The output is: 输出为:

9 Tom Grapes 28
10 Ben Lemon 21
11 Paul Lime 37

Next cool file

cat: yang: Is a directory
cat: ying: Is a directory

I want to remove these 'error-messages', so I tried: 我想删除这些“错误消息”,所以尝试了:

cat *[!/]

But it just returns: 但是它只是返回:

cat: '*[!/]': No such file or directory

But the other way around: 但是反过来:

cat */

prints only: 仅打印:

cat: yang: Is a directory
cat: ying: Is a directory

Does this mean everything even files end with a slash? 这是否意味着所有文件甚至都以斜杠结尾? If yes, is there a way to differentiate between files and directories? 如果是,是否有办法区分文件和目录? If not, why does this wild card not work? 如果没有,为什么此通配符不起作用?

PS: I'm using Linux PS:我正在使用Linux

find -maxdepth 1 -type f -exec cat {} +

Edit: 编辑:

To ignore hidden files 忽略隐藏文件

find -maxdepth 1 -type f -name '[!.]*' -exec cat {} +

Reference: Exclude hidden files when searching with Unix/Linux find? 参考: 使用Unix / Linux查找时排除隐藏文件吗?

Any expression like * only refers to the file name itself, not the type. 任何类似*表达式仅指文件名本身,而不是类型。 Unless you have a distinct naming convention (eg files all have an extension, directories never do) it will be hard to distinguish between files and directories based on their name. 除非您有不同的命名约定(例如,文件都具有扩展名,而目录则没有),否则将很难根据文件和目录的名称来区分它们。

The trailing / is not part of the name. 尾部的/不属于名称。

Quick and dirty solution: 快速而肮脏的解决方案:

cat * 2>/dev/null

This addition just suppresses all error messages. 此添加仅禁止显示所有错误消息。 (Actually, it re-routes them to the void.) (实际上,它会将它们重新路由到空白处。)

If I wanted to do it properly, this would be my first step. 如果我想正确地做,这是我的第一步。 It might not be the best solution, but it goes through all entries in the directory, checks whether it's a file, and only cat those. 它可能不是最好的解决方案,但它会遍历目录中的所有条目,检查它是否是文件,仅cat那些条目。

for f in *; do
    if [[ -f $f ]]; then
        cat $f
    fi
done

Which can be written in one line: 可以写成一行:

for f in *; do if [[ -f $f ]]; then cat $f; fi; done

Maybe someone else here has a better idea. 也许其他人有更好的主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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