linux 删除包含字符串,删除文件中包含字符串的文件-Linux CLI

本文介绍了一种处理包含空格及特殊字符文件名的搜索与移动方法,通过使用特定命令组合避免了因文件名格式导致的问题。此外,还提供了解决UTF-16编码文件中grep匹配问题的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我喜欢马丁·贝克特(Martin Beckett)的解决方案,但发现带有空格的文件名可能会使它崩溃(例如谁在文件名中使用空格pfft:D)。 我还想查看匹配的内容,所以我将匹配的文件移动到本地文件夹,而不是仅使用“ rm”命令删除它们:

# Make a folder in the current directory to put the matched files

$ mkdir -p './matched-files'

# Create a script to move files that match the grep

# NOTE: Remove "-name '*.txt'" to allow all file extensions to be searched.

# NOTE: Edit the grep argument 'something' to what you want to search for.

$ find . -name '*.txt' -print0 | xargs -0 grep -al 'something' | awk -F '\n' '{ print "mv \""$0"\" ./matched-files" }' > doit.sh

Or because its possible (in Linux, idk about other OS's) to have newlines in a file name you can use this longer, untested if works better (who puts newlines in filenames? pfft :D), version:

$ find . -name '*.txt' -print0 | xargs -0 grep -alZ 'something' | awk -F '\0' '{ for (x=1; x doit.sh

# Evaluate the file following the 'source' command as a list of commands executed in the current context:

$ source doit.sh

注意:我遇到grep无法在具有utf-16编码的文件内匹配的问题。解决方法请参见此处。 如果网站消失了,您可以使用grep的-a标志,该标志使grep将文件视为文本,并使用与每个扩展字符中的任何第一个字节匹配的正则表达式模式。 例如,要匹配Entité,请执行以下操作:

grep -a 'Entit.e'

如果这不起作用,请尝试以下操作:

grep -a 'E.n.t.i.t.e'

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值