Bash globbing - autoexpand for a few specific cases?

本秂侑毒 提交于 2020-01-10 10:22:13

问题


I understand that the wildcard * (by itself) will expand in such a way that it means "all non-hidden files in the current folder" with hidden files being those prefixed by a period.

There are two use cases that I would think are useful, but I don't know how to properly do:

  1. How can you glob for... "All files in the current folder, including hidden files, but not including . or .."?

  2. How can you glob for... "All hidden files (and only hidden files) in the current folder, but not including . or .."?


回答1:


To expand on paviums answer and answer the second part of your question, all files except . and .. could be specified like this:

{.[!.]*,*}

Depending on your exact use case it might be better to set the dotglob shell option, so that bash includes dotfiles in expansions of * by default:

$ shopt -s dotglob
$ echo *
.tst



回答2:


The Bash Cookbook suggests a solution to your 2nd requirement.

.[!.]*

as a way of specifying 'dot files' but avoiding . and ..

Of course, ls has the -A option, but that's not globbing.




回答3:


To meet your first case:

echo {.,}[^.]*

or

echo {.,}[!.]*

Edit:

This one seems to get everything, but is shorter than ephemient's

echo {.*,}[^.]*



回答4:


Combining sth and pavium answers

# dot files but avoiding . and ..
.[!.]*

# all files but avoiding . and .. 
{.[!.]*,*}



回答5:


By "all files" and "all hidden files" do you mean files-only, or do you mean both files and directories? Globbing operates on names irrespective of it belonging to a file or a directory. The other folks give good answers for using globbing to find hidden vs non-hidden names, but you may want to turn to the find command as an easier alternative that can distinguish between the types.

To find "All files in the current folder, including hidden files, but not including . or ..":

find . -type f

To find "All files and directories in the current folder, including hidden files, but not including . or ..":

find . ! -name .

To find "All hidden files (and only hidden files) in the current folder, but not including . or ..":

find . -name '.*' -type f

To find "All hidden files and directories (and only hidden files and directories) in the current folder, but not including . or ..":

find . -name '.*' ! -name .

Note that by default find will recurse through subdirectories, too, so if you want to limit it to only the current directory you can use:

find . -maxdepth 1 -type f



回答6:


So, even though this is old - without using shopt, this doesn't seem to have been answered fully. But, expanding on what has been given as answers so far, these work for me:

1:

{*,.[!.]*,..?*}

2:

{.[!.]*,..?*}



来源:https://stackoverflow.com/questions/1586477/bash-globbing-autoexpand-for-a-few-specific-cases

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