案例1:
使用for循环结构在/oldboy目录下创建10个文件,名称依次为:
chang-1
chang-2
chang-3
...
chang-10
脚本:
[root@vm1 scripts]# cat for9.sh
#!/bin/bash
[ -d "/chang" ] || mkdir /chang
cd /chang
for i in {1..10}
do
touch changchunhua-${i}
if [ $? -eq 0 ]
then
echo "create file changchunhua-${i} successfully."
fi
done
运行情况:
[root@vm1 scripts]# sh for9.sh
create file changchunhua-1 successfully.
create file changchunhua-2 successfully.
create file changchunhua-3 successfully.
create file changchunhua-4 successfully.
create file changchunhua-5 successfully.
create file changchunhua-6 successfully.
create file changchunhua-7 successfully.
create file changchunhua-8 successfully.
create file changchunhua-9 successfully.
create file changchunhua-10 successfully.
然后再到/chang目录下检查结果:
案例2:使用for循环将上面的changchunhua替换为linux,并且将扩展名改成大写。要求:for循环的循环体不能出现oldboy字符串。
renanme “changchunhua” "linux" changchunhua*
rename命令的用法:
rename fromstring tostring files
我看到一个网页上有rename跟正则表达式相结合的用法,但是检查man rename的方法,没有看到。在centos7的linux系统中测试了一下也是不行的。
然后再使用命令:
for filename in `ls linux*`;do mv $filename ${filename}.HTML;done
我们再将这个大写字母,改成小写字母:
rename ".HTML" ".html" linux*
或:
rename ".HTML" ".html" *.HTML
使用sed命令:
for filename in `ls /chang/*.html`; do mv $filename `echo $filename | sed "s#changchunhua#linux#g" | sed "s#html#HTML#g"`;done
测试结果如下:
还有别的方法: