How to exclude this / current / dot folder from fi

2019-03-07 20:36发布

find . -type d

can be used to find all directories below some start point. But it returns the current directory (.) too, which may be undesired. How can it be excluded?

4条回答
虎瘦雄心在
2楼-- · 2019-03-07 21:03

Well, a simple workaround as well (solution was not working for me on git bash)

find * -type d

It might not be very performant, but gets the job done, and it's what we need sometimes.

查看更多
三岁会撩人
3楼-- · 2019-03-07 21:06

I use find ./* <...> when I don't mind ignoring first-level dotfiles (the * glob doesn't match these by default in bash - see the 'dotglob' option in the shopt builtin: https://www.gnu.org/software/bash/manual/html_node/The-Shopt-Builtin.html).

eclipse tmp # find .
.
./screen
./screen/.testfile2
./.X11-unix
./.ICE-unix
./tmux-0
./tmux-0/default
eclipse tmp # find ./*
./screen
./screen/.testfile2
./tmux-0
./tmux-0/default
查看更多
可以哭但决不认输i
4楼-- · 2019-03-07 21:12

Not only the recursion depth of find can be controlled by the -maxdepth parameter, the depth can also be limited from “top” using the corresponding -mindepth parameter. So what one actually needs is:

find . -mindepth 1 -type d
查看更多
不美不萌又怎样
5楼-- · 2019-03-07 21:22

POSIX 7 solution:

find . ! -path . -type d

For this particular case (.), golfs better than the mindepth solution (24 vs 26 chars), although this is probably slightly harder to type because of the !.

To exclude other directories, this will golf less well and requires a variable for DRYness:

D="long_name"
find "$D" ! -path "$D" -type d

My decision tree between ! and -mindepth:

  • script? Use ! for portability.
  • interactive session on GNU?
    • exclude .? Throw a coin.
    • exclude long_name? Use -mindepth.
查看更多
登录 后发表回答