bash脚本用于创建文件夹和移动文件

时间:2016-09-23 14:53:11

标签: linux bash shell

我有很多从模拟中创建的文件 像这样:res_00001.root到res_09999.root。

我想创建一系列文件夹,这些文件夹按顺序移动到一个新创建的文件夹中,基于我们正在移动的文件名。例如folder1将包含res_00001.root到res_00999.root,folder2 res_01000.root到res_01999.root,...

我尝试创建一个脚本,但它不起作用:

#!/bin/bash
N_files=$1
for (( file=0; file<$N_files; ++file )) do #state what file I am looking at
  s=file%1000 INPUT=printf data/output_%04lu.root $file` OUTPUT=printf data/folder%02lu/res_%04lu.root $s # move the files
  mv INPUT OUTPUT
done`

我一直在反对这个问题,我感谢您提供的任何帮助。

1 个答案:

答案 0 :(得分:0)

更新了答案

如果找不到rename程序,可以运行这个小脚本 - 先备份!

#!/bin/bash
shopt -s nullglob nocaseglob
for f in *.root; do
   n=$(tr -dc '[0-9]' <<< $f)
   ((d=(10#$n/1000)+1))
   [ ! -d folder$d ] && mkdir folder$d
   echo mv "$f" folder$d/$f
done

原始答案

进行备份,看看这是否可以帮助您复制一小部分文件:

rename --dry-run 's/[^0-9]//g; my $d=int($_/1000)+1; $_="folder$d/res_$_.root"' *root 

示例输出

'res_00001.root' would be renamed to 'folder1/res_00001.root'
'res_00002.root' would be renamed to 'folder1/res_00002.root'
'res_00003.root' would be renamed to 'folder1/res_00003.root'
'res_00004.root' would be renamed to 'folder1/res_00004.root'
'res_00005.root' would be renamed to 'folder1/res_00005.root'
...
...
'res_00997.root' would be renamed to 'folder1/res_00997.root'
'res_00998.root' would be renamed to 'folder1/res_00998.root'
'res_00999.root' would be renamed to 'folder1/res_00999.root'
'res_01000.root' would be renamed to 'folder2/res_01000.root'
'res_01001.root' would be renamed to 'folder2/res_01001.root'
'res_01002.root' would be renamed to 'folder2/res_01002.root'
'res_01003.root' would be renamed to 'folder2/res_01003.root'
...
...

如果它看起来不错,请移除--dry-run,这样它实际上就可以完成,而不仅仅是说 会做什么!

  • s/[^0-9]//g删除文件名中的任何非数字
  • my $d=int($_/1000)+1计算目录名称
  • $_="folder$d/res_$_.root"构建输出文件名