我在UNIX的一个目录下有几百个PDF。PDF的名称非常长(约60个字符)。
当我尝试使用以下命令一起删除所有PDF时:
rm -f *.pdf
我收到以下错误:
/bin/rm: cannot execute [Argument list too long]
此错误的解决方案是什么?mv和cp命令是否也会出现此错误?如果是,如何解决这些命令?
我在UNIX的一个目录下有几百个PDF。PDF的名称非常长(约60个字符)。
当我尝试使用以下命令一起删除所有PDF时:
rm -f *.pdf
我收到以下错误:
/bin/rm: cannot execute [Argument list too long]
此错误的解决方案是什么?mv和cp命令是否也会出现此错误?如果是,如何解决这些命令?
当前回答
我发现对于非常大的文件列表(>1e6),这些答案太慢了。这里有一个在python中使用并行处理的解决方案。我知道,我知道,这不是linux。。。但这里没有其他办法奏效。
(这节省了我几个小时)
# delete files
import os as os
import glob
import multiprocessing as mp
directory = r'your/directory'
os.chdir(directory)
files_names = [i for i in glob.glob('*.{}'.format('pdf'))]
# report errors from pool
def callback_error(result):
print('error', result)
# delete file using system command
def delete_files(file_name):
os.system('rm -rf ' + file_name)
pool = mp.Pool(12)
# or use pool = mp.Pool(mp.cpu_count())
if __name__ == '__main__':
for file_name in files_names:
print(file_name)
pool.apply_async(delete_files,[file_name], error_callback=callback_error)
其他回答
查找具有-delete操作:
find . -maxdepth 1 -name '*.pdf' -delete
或者您可以尝试:
find . -name '*.pdf' -exec rm -f {} \;
删除目录/path/To/dir_with_pdf_files中的所有*.pdf/
mkdir empty_dir # Create temp empty dir
rsync -avh --delete --include '*.pdf' empty_dir/ /path/to/dir_with_pdf_files/
如果您有数百万个文件,使用通配符通过rsync删除特定文件可能是最快的解决方案。它会解决你遇到的错误。
(可选步骤):干运行。检查将删除而不删除的内容`
rsync -avhn --delete --include '*.pdf' empty_dir/ /path/to/dir_with_pdf_files/
...
单击rsync提示和技巧以获取更多rsync黑客
我遇到过几次这个问题。许多解决方案将为每个需要删除的文件运行rm命令。这是非常低效的:
find . -name "*.pdf" -print0 | xargs -0 rm -rf
我最终编写了一个python脚本,根据文件名中的前4个字符删除文件:
import os
filedir = '/tmp/' #The directory you wish to run rm on
filelist = (os.listdir(filedir)) #gets listing of all files in the specified dir
newlist = [] #Makes a blank list named newlist
for i in filelist:
if str((i)[:4]) not in newlist: #This makes sure that the elements are unique for newlist
newlist.append((i)[:4]) #This takes only the first 4 charcters of the folder/filename and appends it to newlist
for i in newlist:
if 'tmp' in i: #If statment to look for tmp in the filename/dirname
print ('Running command rm -rf '+str(filedir)+str(i)+'* : File Count: '+str(len(os.listdir(filedir)))) #Prints the command to be run and a total file count
os.system('rm -rf '+str(filedir)+str(i)+'*') #Actual shell command
print ('DONE')
这对我来说非常有效。我能够在大约15分钟内清除一个文件夹中超过200万个临时文件。我从一点点代码中对tar进行了注释,这样任何一个对python一无所知的人都可以操作这段代码。
使用GNU并行(sudo apt install parallel)非常简单
它以多线程方式运行命令,其中“{}”是传递的参数
E.g.
ls/tmp/myfiles*|并行“rm{}”