Bash globbing - autoexpand for a few specific cases?

前端 未结 6 1110
半阙折子戏
半阙折子戏 2020-12-29 13:05

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 thos

相关标签:
6条回答
  • 2020-12-29 13:59

    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
    
    0 讨论(0)
  • 2020-12-29 14:00

    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
    
    0 讨论(0)
  • 2020-12-29 14:03

    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:

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

    0 讨论(0)
  • 2020-12-29 14:04

    Combining sth and pavium answers

    # dot files but avoiding . and ..
    .[!.]*
    
    # all files but avoiding . and .. 
    {.[!.]*,*}
    
    0 讨论(0)
  • 2020-12-29 14:08

    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.

    0 讨论(0)
  • 2020-12-29 14:08

    To meet your first case:

    echo {.,}[^.]*
    

    or

    echo {.,}[!.]*
    

    Edit:

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

    echo {.*,}[^.]*
    
    0 讨论(0)
提交回复
热议问题