今天的内容主要为:批量建立文件,批量重命名文件,批量删除文件。
主要通过循环操作来实现批量这个功能。
基本知识点:新建文件,删除文件和重命名文件的命令:touch,rm,mv,
案例:
[cpp] view plain copy
- #! /bin/bash
- echo "-----------------the starting line of shell-----------------"
- # create new files
- for name in Test{1..3}.h
- do
- touch $name
- done
- #show the files, which is created
- for name in *.h
- do
- echo $name
- done
- #rename the files
- i=0
- for name in *.h
- do
- newname=${name%.*}-$i
- mv "$name" "$newname.h"
- let i++
- done
- #show the new files, which is renamed
- for name in *.h
- do
- echo $name
- done
- #remove the files
- for name in *.h
- do
- rm -rf $name
- done
- echo "-----------------the ending line of shell-----------------"
在终端中运行该程序可以得到以下的结果:
-----------------the starting line of shell-----------------
Test1.h
Test2.h
Test3.h
Test1-0.h
Test2-1.h
Test3-2.h
-----------------the ending line of shell-----------------
通过for循环操作实现了批量功能。该脚本文件会在脚本文件所在的目录中新建立文件,也可以把它放到自己定义的目录执行。该脚本中没有指定专门的目录,在显示文件的时候,也是会遍历脚本所在目录中的.h文件,所以会把脚本第一阶段建立的.h文件显示出来。该方法在重命名和删除文件时候也在使用。
另外:在重命名的时候,name%.*表示把变量值中.前面的内容提取出来。.后面是*表示匹配。例如:name的值是test1.h.经过提取后会得到test1,.h被舍弃。
还有一种方法:name#*.它表示把变量值中.后面的内容提取出来。例如:name的值是test1.h.经过提取后会得到h,test1.会被舍弃。该方法在提取文件名,或者文件后缀时很有用。