linux if 数字大小写,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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值