例1,批量修改文件后缀名。
复制代码 代码示例:
#!/bin/bash
ldext="jpg"
newext="jpg"
dir=$(eval pwd)
for file in $(ls $dir | grep .$oldext)
do
name=$(ls $file | cut -d. -f1)
mv $file ${name}.$newext
done
echo "change jpg=====>jpg done!"
说明:
1.变量oldext和newext分别指定旧的扩展名和新的扩展名。dir指定文件所在目录;
2.“ls $dir | grep .$oldext”用来在指定目录dir中获取扩展名为旧扩展名的所有文件;
3.在循环体内先利用cut命令将文件名中“.”之前的字符串剪切出来,并赋值给name变量;接着将当前的文件名重命名为新的文件名。
通过这个脚本,所有照片的扩展名都成功修改。
可以增加几条read命令实现脚本和用户之间的交互。改进版的脚本:
复制代码 代码示例:
#!/bin/bash
# www.jb200.com
read -p "old extension:" oldext
read -p "new extension:" newext
read -p "the directory:" dir
cd $dir
for file in $(ls $dir | grep .$oldext)
do
name=$(ls $file | cut -d. -f1)
mv $file ${name}.$newext
echo "$name.$oldext ====> $name.$newext"
done
echo "all files has been modified."
shell/ target=_blank class=infotextkey>shell脚本3:
复制代码 代码示例:
#!/bin/sh
# file name : rename_suffix.sh
# author: zhouhh
# email: ablozhou@gmail.com
# date : 2008.4.1
echo "input what suffix will be replaced :"
read suffix_src
echo "input what suffix of file to rename to:"
read suffix_dst
for i in *.$suffix_src
do
if [ -e $i ]; then
echo "mv $i to `basename $i .$suffix_src`.$suffix_dst"
mv $i `basename $i .$suffix_src`.$suffix_dst
else
echo "file does not exist."
exit -1
fi
done
第二部分,shell脚本批量修改当前目录下的文件名
批量修改当前目录下的文件名
复制代码 代码示例:
#!/bin/sh
for fname in *;do
tmp=`echo $fname|tr [a-z] [a-z]` #note ,tr can't act like this: tr fname [a-z] [a-z]'因为它只从标准输入读取数据
# it must run as this'tr
#the above code cost me lots of time!
第三部分,linux下批量统计文本文件行数的shell脚本
统计其实很简单,就一行,把批量循环也记下来:
lines.sh
复制代码 代码示例:
#!/bin/bash
# 51 us states
db=(ak al ar az ca co ct dc de fl ga hi ia id il in ks ky la ma md me mi mn mo ms mt nc nd ne nh nj nm nv ny oh ok or pa ri sc sd tn tx ut va vt wa wi wv wy)
for i in "${db[@]}";do
echo ---------- $i ----------
wc -l /var/www/html/example.com/sites/$i.tsv
done