微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

shell 整理27===大小写字母替换修改文件名

(一)题目:

(1)创建一个文件

(2)文件夹里面有10 个以任意字母或数字开头的文件

(3)如果开头第一位数字就不做改变

(4)如果开头第一位字母就改成大写

例如:修改后的结果

[root@localhost hushuai]# ls

06e28fe4 5b1775ab 74d1badf Cccb27b2 F3619201

3bfaa07c 6bd6b971 C4a1f7d8 Db3308c4 F6403885

[root@localhost hushuai]#


shell 代码如下:

#!/bin/bash


a=`ls hushuai/ |xargs -n1`

echo "$a" |while read line         #这个地方必须加双引号,细节,不加不解析空格

do

b=`echo $line | cut -c1`

c=`echo $line |cut -c2-`

d=`echo $b |grep -c '[a-z]'`#必须加[],和tr 不一样

if [ $d -eq 1 ];then

e=`echo $b | tr 'a-z' 'A-Z'`

mv hushuai/$b$c hushuai/$e$c 2>/dev/null

fi# mv 旧名字 新名字

done

这样写显得没有条理,纷繁复杂,我们可以把判断改成函数修改结果如下:

#!/bin/bash



swap(){ b=`echo $line | cut -c1`

c=`echo $line |cut -c2-`

d=`echo $b |grep -c '[a-z]'`

}

a=`ls hushuai/ |xargs -n1`

echo "$a" |while read line

do

swap

if [ $d -eq 1 ];then

e=`echo $b | tr 'a-z' 'A-Z'`

mv hushuai/$b$c hushuai/$e$c 2>/dev/null

fi#如果说你执行多次脚本,名字第一次已经改过来了

done就会报错,我们让错误输出到空


然后我们给这个题目做一下升级

(1)创建一个文件

(2)文件夹里面有10以dingxue为开头的任意6-10位随机数组成

(3)把dingxue 的首字母ding 换成任意一个大写字母

(4)把后面的6-10位随机数换成等长度的小写字母

例如:


[root@localhost hushuai]# ls ding/

dingxue87495987 dingxue885527619 dingxue894674790 dingxue908168

dingxue87819699 dingxue8884654 dingxue8974959

dingxue8810688 dingxue89173327 dingxue903851012

shell 代码如下:

#!/bin/bash


#for i in `seq 10`

#do

# b=$((RANDOM%4+6))     #随机数的应用

# a=`date +%N`

# c=`echo $a | cut -c1-$b`

# touch dingxue$c

#done


a=`ls ding/ |xargs -n1`

echo {A..Z} |xargs -n1>file

d=`cat file | wc -l`

echo "$a" |while read line

do

e=$((RANDOM%$d+1))

 w=`echo $line |awk -F '[0-9]' '{print $1}'`

  b=`echo $line | cut -c 1`

  f=`cat file | sed -n ''$e'p'`

  g=`echo $w |sed 's/'$b'/'$f'/'` #sed 、awk 引用变量都加个单引号

#echo $g具体情况具体定

  h=`echo $line| awk -F'[a-z]' '{print $8}'`

i=`echo $h |tr ''$h'' 'a-z'`#这里也是,一定要注意我的引号

echo $g$i

done

这是我刚开始写的,是不是看上去很乱呢,我们可以把判断部分改成函数修改结果如下:

shell 代码


#!/bin/bash


prepare() {

a=`ls ding/ |xargs -n1`

echo {A..Z} |xargs -n1>file

d=`cat file | wc -l`

}

random () {

e=$((RANDOM%$d+1))

}

virable () {

w=`echo $line |awk -F '[0-9]' '{print $1}'`

b=`echo $line | cut -c 1`

f=`cat file | sed -n ''$e'p'`

g=`echo $w |sed 's/'$b'/'$f'/'`

h=`echo $line| awk -F'[a-z]' '{print $8}'`

i=`echo $h |tr ''$h'' 'a-z'`

}

prepare

echo "$a" |while read line

do

random

virable

echo $g$i

done

这样是不是清晰了很多了呢?

原文地址:https://www.jb51.cc/bash/390430.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐