项目总结-Linux下批量删除无用文件
2017-06-13 09:51
411 查看
背景
有一个功能,需要定期清理指定文件夹下指定日期的无用文件,文件的存储格式是目录/yyyyMMddHH/xx.txt,文件夹以小时命名的,现在要定期删除某些日期的文件。用java调用Shell命令的rm -rf 目录/日期*的方式总数不成功,初步判断正则表达式没有匹配成功,所以没有执行删除操作。解决办法
编写一个Shell脚本文件来删除,参数传递需要删除的日期列表,然后循环拼接删除命令完成操作,如下Shell文件命名为rmfile.sh。#!/bin/sh basePath=$1 dates=$2 date=${dates//,/ } for element in $date do echo $basePath*/$element* rm -rf $basePath*/$element* done
例如:用Java的Process调用该Shell脚本文件,传递参数,示例代码:
rmfile.sh /mydata/ 20170613,20170614
之所以想起总结这个简单问题,是因为早上看到了一篇介绍Shell的循环结构的文章,刚刚想起这个简单脚本中用到了for循环,也是巩固学习的过程。
补充
Java调用Shell文件的简单方法代码如下:public static List<String> executeShell(String shpath, String var){ String shellVar = (var==null)?"":var; String command1 = "chmod 777 " + shpath; // 为 sh 添加权限 String command2 = "/bin/sh " + shpath + " " + shellVar; log.debug("执行shell脚本开始:"+command2); List<String> strList = new ArrayList<String>(); Process process = null; BufferedReader in = null; try { process = Runtime.getRuntime().exec(command1); // 执行添加权限的命令 process.waitFor(); // 如果执行多个命令,必须加上 process = Runtime.getRuntime().exec(command2); process.waitFor(); in = new BufferedReader(new InputStreamReader(process.getInputStream())); String str = null; while ((str = in.readLine()) != null) { strList.add(str); } } catch (IOException e) { } catch (InterruptedException e) { }finally { if(in != null){ try { in.close(); } catch (IOException e) { } } if(process != null){ process.destroy(); } } return strList; }
说明:如果需要同步等待Shell文件的执行结果必须有process.waitFor(); 这个操作。
相关文章推荐
- linux技巧总结之--tar文件的批量加压
- 批量删除多台linux服务器文件
- Linux批量删除大量文件的命令
- Linux下批量删除空文件
- Linux 批量删除指定后缀的文件
- linux 批量删除及修改文件shell命令
- Linux如何快速删除项目中的svn隐藏文件
- windows/linux 下删除项目中svn文件
- Linux下删除无用的(很久没有访问或者修改)的文件
- 项目总结(四)----------Python实现Windows和Linux之间互相传输文件(文件夹)
- Linux下通配符批量删除相同文件
- linux系统中的批量删除文件与空文件删除的命令介绍
- (转)linux 批量删除文件命令
- linux下快速删除文件批量删除文件
- Linux下批量删除文件(find和rm结合)
- (总结)Linux下使用rsync最快速删除海量文件的方法
- linux下批量删除空文件
- linux快速删除批量文件
- linux下批量删除指定后缀的文件
- Linux删除破折号开头的文件与Windows下批量去掉文件的隐藏属性