![find를 사용하여 디렉터리를 찾고 해당 하위 디렉터리를 삭제하세요.](https://linux55.com/image/111667/find%EB%A5%BC%20%EC%82%AC%EC%9A%A9%ED%95%98%EC%97%AC%20%EB%94%94%EB%A0%89%ED%84%B0%EB%A6%AC%EB%A5%BC%20%EC%B0%BE%EA%B3%A0%20%ED%95%B4%EB%8B%B9%20%ED%95%98%EC%9C%84%20%EB%94%94%EB%A0%89%ED%84%B0%EB%A6%AC%EB%A5%BC%20%EC%82%AD%EC%A0%9C%ED%95%98%EC%84%B8%EC%9A%94..png)
다음과 같은 중첩된 디렉터리 목록이 있다고 가정해 보겠습니다.
./x1/mf/dir1
./x1/mf/dir2
./x1/mf/file1
./x2/mf/dir3
./x2/mf/file2
...
mf
각 디렉토리의 하위 디렉토리를 모두 삭제하고 싶습니다 . dir1
이전 예에서 의미합니다 .dir2
dir3
알아요
find . -type d -name "mf"
라는 이름의 모든 디렉토리 목록을 반환합니다 mf
. 그리고 ls -d */
현재 디렉터리 아래의 모든 하위 디렉터리를 반환합니다. 그래서 나는 노력했다
find . -type d -name "mf" -exec ls -d /* {} \;
원하는 디렉토리를 나열하지만 실제로는 /
결과 목록을 파이프하여 xargs rm -r
나중에 삭제하려고 합니다.
답변1
테스트 디렉터리 및 파일을 설정합니다.
$ mkdir -p x{1..3}/mf/dir{1..3}
$ touch x{1..3}/mf/file{1..3}
$ tree
.
|-- x1
| `-- mf
| |-- dir1
| |-- dir2
| |-- dir3
| |-- file1
| |-- file2
| `-- file3
|-- x2
| `-- mf
| |-- dir1
| |-- dir2
| |-- dir3
| |-- file1
| |-- file2
| `-- file3
`-- x3
`-- mf
|-- dir1
|-- dir2
|-- dir3
|-- file1
|-- file2
`-- file3
그런 다음 해당 경로에서 모든 디렉터리를 찾아 mf
삭제합니다. -depth
깊이 우선 순회를 수행하므로 삭제 find
된 디렉터리에 들어가려는 시도가 이루어지지 않습니다. 또한 삭제된 모든 디렉토리의 이름도 인쇄합니다.
$ find . -depth -type d -path "*/mf/*" -print -exec rm -rf {} +
./x1/mf/dir1
./x1/mf/dir2
./x1/mf/dir3
./x2/mf/dir1
./x2/mf/dir2
./x2/mf/dir3
./x3/mf/dir1
./x3/mf/dir2
./x3/mf/dir3
지금:
$ tree
.
|-- x1
| `-- mf
| |-- file1
| |-- file2
| `-- file3
|-- x2
| `-- mf
| |-- file1
| |-- file2
| `-- file3
`-- x3
`-- mf
|-- file1
|-- file2
`-- file3
답변2
분명한 이유로 ing ls
전에 사용하는 것이 좋습니다 .rm -fr
find . -type d -name "mf" -print0 | xargs -0 -n1 -I haystack find haystack -type d -exec rm -fr {} \;
예:
$ tree
.
├── bar
│ ├── foo
│ │ ├── bar
│ │ └── baz
│ └── freeble
├── baz
│ ├── foo
│ │ ├── bar
│ │ └── baz
│ └── freeble
└── quux
├── foo
│ ├── bar
│ └── baz
└── freeble
15 directories, 0 files
$ find . -type d -name "foo" -print0 | xargs -0 -n1 -I haystack find haystack -type d -maxdepth 0 -exec rm -fr {} \;
$ tree
.
├── bar
│ └── freeble
├── baz
│ └── freeble
└── quux
└── freeble
6 directories, 0 files