Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/unix/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash 递归删除所有“*”。"富",;带有相应“*”的文件。酒吧;文件夹_Bash_Unix_Recursion_Zsh - Fatal编程技术网

Bash 递归删除所有“*”。"富",;带有相应“*”的文件。酒吧;文件夹

Bash 递归删除所有“*”。"富",;带有相应“*”的文件。酒吧;文件夹,bash,unix,recursion,zsh,Bash,Unix,Recursion,Zsh,如何递归删除所有以.foo结尾的文件,这些文件具有同名的同级文件,但以.bar结尾?例如,考虑下面的目录树: . ├── dir │   ├── dir │   │   ├── file4.bar │   │   ├── file4.foo │   │   └── file5.foo │   ├── file2.foo │   ├── file3.bar │   └── file3.foo ├── file1.bar └── file1.foo 在本例中,file.foo,file3.foo和

如何递归删除所有以
.foo
结尾的文件,这些文件具有同名的同级文件,但以
.bar
结尾?例如,考虑下面的目录树:

.
├── dir
│   ├── dir
│   │   ├── file4.bar
│   │   ├── file4.foo
│   │   └── file5.foo
│   ├── file2.foo
│   ├── file3.bar
│   └── file3.foo
├── file1.bar
└── file1.foo
在本例中,
file.foo
file3.foo
file4.foo
将被删除,因为存在同级
文件{1,3,4}.bar
文件<代码>文件{2,5}.foo应单独保留此结果:

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

请记住,在尝试执行此
find
rm
命令之前,先进行备份

使用此
查找

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

bash
4.0及更高版本和
zsh
中:

shopt -s globstar   # Only needed by bash
for f in **/*.foo; do
    [[ -f ${f%.foo}.bar ]] && rm ./"$f"
done
zsh
中,仅当存在相应的
.bar
文件时,才能定义与以
.foo
结尾的文件相匹配的选择性模式,以便
rm
仅调用一次,而不是每个文件调用一次

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

+对于一个说明良好的问题,请参见1。感谢现有的
:P干得好!OP只需注意一点,为了匹配
xargs
的性能,可以使用
+
符号来并行处理文件。+1我不理解
${1%.*}
我在玩游戏,
${1%}
将返回扩展名。我在哪里可以找到更多信息?@Tiago:谢谢你可以在
manbash
下找到
Parameter Expansion
部分。为了以防万一,我总是在这些全局文件名之前使用“-”,用户可能想设置全局点(以获得类似于“find”的结果):
rm-->***.foo(De:'[-f${REPLY%.foo}.bar]]:)
优点。我将答案编辑为使用
/
而不是
--
,因为这将适用于
rm
的任何实现。
shopt -s globstar   # Only needed by bash
for f in **/*.foo; do
    [[ -f ${f%.foo}.bar ]] && rm ./"$f"
done
rm ./**/*.foo(e:'[[ -f ${REPLY%.foo}.bar ]]':)