Recursively deleting all “*.foo” files with corresponding “*.bar” files

徘徊边缘 提交于 2019-12-12 10:52:09

问题


How can I recursively delete all files ending in .foo which have a sibling file of the same name but ending in .bar? For example, consider the following directory tree:

.
├── dir
│   ├── dir
│   │   ├── file4.bar
│   │   ├── file4.foo
│   │   └── file5.foo
│   ├── file2.foo
│   ├── file3.bar
│   └── file3.foo
├── file1.bar
└── file1.foo

In this example file.foo, file3.foo, and file4.foo would be deleted since there are sibling file{1,3,4}.bar files. file{2,5}.foo should be left alone leaving this result:

.
├── dir
│   ├── dir
│   │   ├── file4.bar
│   │   └── file5.foo
│   ├── file2.foo
│   ├── file3.bar
└── file1.bar

回答1:


Remember to first take a backup before you try this find and rm command.

Use this find:

find . -name "*.foo" -execdir bash -c '[[ -f "${1%.*}.bar" ]] && rm "$1"' - '{}' \;



回答2:


while IFS= read -r FILE; do
    rm -f "${FILE%.bar}".foo
done < <(exec find -type f -name '*.bar')

Or

find -type f -name '*.bar' | sed -e 's|.bar$|.foo|' | xargs rm -f



回答3:


In bash 4.0 and later, and in zsh:

shopt -s globstar   # Only needed by bash
for f in **/*.foo; do
    [[ -f ${f%.foo}.bar ]] && rm ./"$f"
done

In zsh, you can define a selective pattern that matches files ending in .foo only if there is a corresponding .bar file, so that rm is invoked only once, rather than once per file.

rm ./**/*.foo(e:'[[ -f ${REPLY%.foo}.bar ]]':)


来源:https://stackoverflow.com/questions/24516644/recursively-deleting-all-foo-files-with-corresponding-bar-files

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