shell批量移动文件

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了shell批量移动文件相关的知识,希望对你有一定的参考价值。

参考技术A

将当前目录下面包括子目录中的png文件移动至指定的target目录

对一个的shell脚本

通常我们使用如下的方式去批量删除文件:

那是否可以采用类似方式通过find命令来批量移动文件呢?

很遗憾,不能采用这种方式来实现
理由: 像cd和ls命令只需要一个input,而像mv和cp等命令都需要两个input,需要source和target。通过管道只能获得一个input。

shell脚本:批量修改文件名(文件名中添加字符)

举例如下:批量创建10个随机字符串的文件,要求每个文件名后面添加_aaa,后缀名不变;

[[email protected] goodboy]# ls

adddbbdedf.html  baacjaiija.html  bhcfaabcfh.html  dgjdcdfbca.html  efejadfdji.html

agdhcdeaje.html  bgffbffjcg.html  cbbiebdafh.html  diadebbhag.html  jcajafgejf.html

脚本1:

[[email protected] ~]# cat 02.sh
#!/bin/bash
#written by [email protected]
path=/goodboy
[ -d $path ] && cd $path
for file in `ls`
do
 mv $file `echo $file|sed ‘s/\(.*\)\.\(.*\)/\1_aaa.\2/g‘`
done


解释说明:

使用sed替换,正则表达式第1个()括号里面代表文件名即\1;中间. 使用\进行脱意,代表分隔符;

第2个括号里面代表后缀html内容即\2;

使用此方法需要在替换中添加.符号;


更改后的效果如下:

[[email protected] goodboy]# ll
-rw-r--r-- 1 root root 0 2月  17 17:40 adddbbdedf_aaa.html
-rw-r--r-- 1 root root 0 2月  17 17:40 agdhcdeaje_aaa.html
-rw-r--r-- 1 root root 0 2月  17 17:40 baacjaiija_aaa.html
-rw-r--r-- 1 root root 0 2月  17 17:40 bgffbffjcg_aaa.html
-rw-r--r-- 1 root root 0 2月  17 17:40 bhcfaabcfh_aaa.html
-rw-r--r-- 1 root root 0 2月  17 17:40 cbbiebdafh_aaa.html
-rw-r--r-- 1 root root 0 2月  17 17:40 dgjdcdfbca_aaa.html
-rw-r--r-- 1 root root 0 2月  17 17:40 diadebbhag_aaa.html
-rw-r--r-- 1 root root 0 2月  17 17:40 efejadfdji_aaa.html
-rw-r--r-- 1 root root 0 2月  17 17:40 jcajafgejf_aaa.html


脚本2:

#!/bin/bash
#written by [email protected]
path=/goodboy
[ -d $path ] && cd $path
for file in `ls`
do
 mv $file `echo $file|sed ‘s/\(.*\)\(\..*\)/\1_aaa\2/g‘`
done


解释说明:

同样使用sed替换,正则表达式,与上面的区别在于第2个括号里面的内容,代表.html 分隔符和后缀名为一体,替换内容的话不需要再单独加.点;.分隔符同样需要使用\进行脱意;


可以使用sed -r参数,看起来就清爽很多,不需要\脱意;

mv $file `echo $file|sed -r ‘s/(.*)(\..*)/\1_aaa\2/g‘`


大家有更好的方法,欢迎分享知识~

本文出自 “模范生的学习博客” 博客,请务必保留此出处http://mofansheng.blog.51cto.com/8792265/1743016

以上是关于shell批量移动文件的主要内容,如果未能解决你的问题,请参考以下文章

PHP 批量移动文件改名

Linux环境下,如何批量移动文件到对应文件夹,文件名和文件夹名都是有序的。

批量移动指定日期范围内的文件

如何批量循环数组并移动文件

批量把子文件夹的文件移动至上一层文件夹

将文件从文件夹批量移动到其他文件夹问题