移动名称中包含空格的多个文件 (Linux)



我有一个目录,其中包含多个名称中带有空格的文件。我想在名称中找到一个模式,这些文件将被移动到其他目录。现在的问题是,当在单个文件名中找到特定模式时,该文件将移动到目标路径,但是当有多个文件时,此方法将失败。以下是我正在使用的代码:

for file in `find . -maxdepth 1 -name "*$pattern*xlsx" -type f`
do
 mv "$file" $destination/
done

无需使用循环:

find . -maxdepth 1 -name "*$pattern*xlsx" -type f -exec mv {} $destination +

使用以下代码工作正常

find . -maxdepth 1 -name "*$pattern*xlsx" -type f -print0 | xargs -I{} -0 mv {} "$destination/"

有时,插入循环主体的逻辑可能足够复杂,以保证实际的 bash 循环。

这是一个以这种方式工作的解决方案:

find . -maxdepth 1 -name "*$pattern*xlsx" -type f | while IFS= read -r file
do
   mv "$file" $destination/
done

编辑:为IFS=@KamilCuk点赞,以处理带有前导和尾随空格的文件名,以及-r,用于处理带有转义退格符的文件名。

已知限制:此解决方案不适用于嵌入换行符的文件名。对于此类情况,请参阅此问题的其他答案。

从注释中的 @Charles Duffy 到移动带有空格的文件的解决方案,即使文件名中的换行符也可以工作:

  • -print0添加到 find 命令以终止具有 NULL 字符的记录
  • -d ''添加到 read 命令以读取由 NULL 终止的记录
find . -maxdepth 1 -name "*$pattern*xlsx" -type f -print0 | while IFS= read -r -d '' file
do
   mv "$file" $destination/
done

find . -maxdepth 1 -name "*$pattern*xlsx" -type f -exec mv {} $destination +的最高答案对我不起作用,find -exec command {} +的手册页如下:

一个实例命令中允许使用"{}",并且它必须出现在末尾,紧接在"+"之前

因此,我建议: find . -maxdepth 1 -name "*$pattern*xlsx" -type f -exec mv -t ../All Exercises/ {} +

最新更新