Linux删除包含abc的文件,如何在Linux上的Bash中一次删除多个文件?

本文介绍了如何使用通配符(glob)和正则表达式安全地删除与特定模式匹配的文件。通过示例展示了`rm -f`命令与`ls`, `grep`结合使用的方法,包括不区分大小写的匹配和确认删除操作,确保正确无误地删除目标文件。此外,还提到了利用临时文本文件编辑和确认要删除的文件列表的技巧。
摘要由CSDN通过智能技术生成

如果要删除名称与特定表单匹配的所有文件,则通配符(glob模式)是最直接的解决方案。 一些例子:

$ rm -f abc.log.* # Remove them all

$ rm -f abc.log.2012* # Remove all logs from 2012

$ rm -f abc.log.2012-0[123]* # Remove all files from the first quarter of 2012

正则表达式比通配符更强大; 您可以将ls | grep ...的输出提供给rm -f.例如,如果某些文件名以"abc.log"开头,而某些文件名以"ABC.log"开头,则grep允许您执行不区分大小写的匹配:

$ rm -f $(ls | grep -i '^abc\.log\.')

When I do this, I run the ls | grep ... command first and check that it produces the output I want -- especially if I'm using rm -f:

$ ls | grep -i '^abc\.log\.'

(check that the list is correct)

$ rm -f $(!!)

其中list扩展为上一个命令。 或者我可以键入向上箭头或Ctrl-P并编辑上一行以添加rm -f命令。

This assumes you're using the bash shell. Some other shells, particularly csh and tcsh and some older sh-derived shells, may not support the list syntax. You can use the equivalent backtick syntax:

$ rm -f `ls | grep -i '^abc\.log\.'`

The list syntax is easier to read, and if you're really ambitious it can be nested.

Finally, if the subset of files you want to delete can't be easily expressed with a regular expression, a trick I often use is to list the files to a temporary text file, then edit it:

$ ls > list

$ vi list # Use your favorite text editor

然后我可以手动编辑list文件,只保留我要删除的文件,然后:

$ rm -f $(

要么

$ rm -f `cat list`

(这假设没有文件名包含有趣的字符,特别是空格。)

或者,在编辑list文件时,我可以将rm -f添加到每行的开头,然后:

$ . ./list

要么

$ source ./list

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值