如何通过终端删除系统中指定名称或关键字的所有内容,以下两种方法实现:
一、通过find命令delete
Please be careful
This following command with the parameter -delete deletes all the files with something in the name in the specified directory and in all subdirectories.
Open a terminal and go to the right folder:
cd [your_search_starts_here]
test with
find . -type f -name "*something*"
and delete with
find . -type f -name "*something*" -delete
Or a shorter version:
find -type f -name "*something*" -delete
For the whole filesystem
!!! first run a test !!!
sudo find / -type f -name "*something*"
and test again and than delete with
sudo find / -type f -name "*something*" -delete
Or only in the specified directory:
find [your_search_starts_here] -maxdepth 1 -type f -name "*something*" -delete
And because you have used the tag locate:
The results of a search with locate are based on a database. This may be outdated. Start an update with sudo updatedb. find performs a true search. However, it also takes longer.
二、使用xargs传递参数
linux中巧用xargs删除另外一个目录中的同名文件
假设有两个目录 /opt/test_a 和 /opt/test_b, /opt/test_b目录下不仅包含了/opt/test_a目录下的文件也包含其他文件,现在要删除/opt/test_b目录中与/opt/test_a目录中同名的文件,但是不删除同名的子目录,可以使用如下命令:
cd /opt/test_a && ls -p | grep -v /$ | xargs -I{} rm -f /opt/test_b/{}
说明:
. ls -p 参数将给列出的目录名最后加上/
. grep -v 参数指定反选择, /$指定以/结尾的搜索模式,因此该命令将输出不带/结尾的项,也就是只输出/opt/test_a目录中的文件名,不包含子目录。
. xargs命令的-I{} 指定用管道传递过来的输入替换后面命令中的{}字符串,重复多次,直至管道没有输入
注:xargs加上 -t 参数,可以看到替换的效果
这个技巧用在makefile中,制作make install 和make uninstall。 对应的make install 执行的命令为:
cd /opt/test_a && ls -p | grep -v /$ | xargs -I{} install -m 755 {} /opt/test_b/
参考:
https://askubuntu.com/questions/625219/how-to-search-and-delete-files-who-contain-specific-string-in-name
https://blog.csdn.net/hansel/article/details/2034102
网友评论