删除以〜结尾的临时文件的命令


15

很多天前,我发现了这个有用的bash别名(〜/ .bash_aliases的内容

# aliases

# finds temporary files ending with '~' and deletes them
alias rm~='find . -name '*~' -print0 | xargs -0 /bin/rm -f'

现在,我尝试rm~cd包含3个文件结尾的目录中使用after~

我在终端中遇到此错误,并且文件未删除

find: paths must precede expression: 1n.in~
Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression]

另外,当我尝试rm~从时/home/me,它似乎什么也没做。否则可能会花费很多时间。

请告诉我为什么会出错,以及如何解决。

谢谢!

Answers:


26

您的bash别名写得不好(单引号没有被很好地使用)。相反,它应该是:

alias rm~='find . -name "*~" -print0 | xargs -0 /bin/rm -f'

现在,我个人不喜欢管道和的无用用法xargs,因此最好将别名写成:

alias rm~='find . -name "*~" -type f -exec /bin/rm -fv -- {} +'

-type f选项仅查找文件(不查找目录,链接等),该-v选项rm仅显示详细信息(打印出要删除的内容)。将+在年底使find运行rm的所有找到的文件(产卵只有一个实例rm,而不是每个文件一个)。

现在来自man bash

对于几乎所有目的,别名都被shell函数取代。

代替别名,最好使用一个函数:在.bash_aliases文件中注释您的别名(即,#在该行的前面),然后在文件中.bashrc,将该函数(在文件的任何位置,最后都可以) :

rm~() {
    find . -name "*~" -type f -exec /bin/rm -fv -- {} +
}

另外,如其他答案所述,您可以使用-delete命令进行查找。在这种情况下,您的rm~功能将是:

rm~() {
    find . -name "*~" -type f -printf "Removing file %p\n" -delete
}

实际上,您可以使一个很酷的函数带有一个参数,例如--dry-run,仅输出将要删除的内容:

rm~() {
    case "$1" in
    "--dry-run")
        find . -name "*~" -type f -printf "[dry-run] Removing file %p\n"
        ;;
    "")
        find . -name "*~" -type f -printf "Removing file %p\n" -delete
        ;;
    *)
        echo "Unsupported option \`$1'. Did you mean --dry-run?"
        ;;
    esac
}

然后用作:

rm~ --dry-run

只显示将要删除的文件(但不删除它们),然后

rm~

当您对此感到满意时。

适应并扩展您的需求!

注意。您必须打开一个新终端才能使更改生效。


谢谢!它运行良好,并且空运行非常有用。
Vinayak Garg

2
find -type f -name '*~' -delete(除了武器以外git clean -dfx .
sehe 12:59

2
这是一个如此优雅的解决方案,我只需要登录即可提供道具。+1,我的好伙伴!
CodeChimp 2012年

9

*~在被分配给您的别名之前由外壳程序扩展。实际的分配是:

alias rm~='find .name some~ file~ 1n.in~ -print0 | xargs -0 /bin/rm -f'

我建议使用函数而不是别名,这些函数在引用方面要强大得多且易于处理。

在执行此操作时,请删除多余的文件.(如果未提供任何参数,则隐含当前目录)并停止滥用,xargs因为-delete已经存在一个选项。

rm~() { find -name '*~' -ls -delete; }

-ls选项是可选的,但添加该选项将显示已删除的文件。


+1谢谢!但是我应该在哪里添加此功能?
Vinayak Garg

@VinayakGarg您也可以将其添加到您的文件中.bash_aliases,但是我通常将它们直接放在我的文件中.bashrc
Lekensteyn
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.