企业面试题2:
使用for循环在/oldboy目录下通过随机小写10个字母加固定字符串oldboy批量创建10个html文件,名称例如为:
1
2
3
4
5
6
|
[root@oldboy oldboy] # sh /server/scripts/oldboy.sh [root@oldboy oldboy] # ls coaolvajcq_oldboy.html qnvuxvicni_oldboy.html vioesjmcbu_oldboy.html gmkhrancxh_oldboy.html tmdjormaxr_oldboy.html wzewnojiwe_oldboy.html jdxexendbe_oldboy.html ugaywanjlm_oldboy.html xzzruhdzda_oldboy.html qcawgsrtkp_oldboy.html vfrphtqjpc_oldboy.html |
答案:题目很简单,主要考察随机数和for或者while循环。随机数都可以用md5sum来产生及tr对数字进行替换。openssl rand -base64 8 也是可以产生的。
如果需要产生特殊字符,可以安装expect,yum install expect,然后用mkpasswd -l 8产生8位的含特殊字符的密码或其他。
[root@nfs_server test]# cat /server/scripts/shell2.sh #!/bin/bash mkdir /root/clc/test -p for n in {1..10} do a=`echo $RANDOM|md5sum |tr [0-9] [a-z]|cut -c 1-8` touch /root/clc/test/"$a"_oldboy.html
done [root@nfs_server test]# [root@nfs_server scripts]# sh shell2.sh [root@nfs_server scripts]# cd /root/clc/test/ [root@nfs_server test]# ls acjfghda_oldboy.html dabjbdjb_oldboy.html adcbajjf_oldboy.html efbfaagg_oldboy.html aifdadai_oldboy.html eifdabhe_oldboy.html ceaedabb_oldboy.html fdgfbffe_oldboy.html chfdfjea_oldboy.html fffffccf_oldboy.html
将以上文件名中的oldboy全部改成oldgirl(用for循环实现),并且html改成大写。
分析:输出名字的方式有,echo,注意不要把文件名的输入出与查看文件这两个搞混淆了。还有这题有一个命令的应用就是:rename,使用起来很方便。
答案一、以下是在命令行实现的。
[root@nfs_server test]# ls|awk -F '_' '{print "mv " $0,$1"_oldboy.html"}' mv acjfghda_oldgirl.HTML acjfghda_oldboy.html mv adcbajjf_oldgirl.HTML adcbajjf_oldboy.html mv aifdadai_oldgirl.HTML aifdadai_oldboy.html mv ceaedabb_oldgirl.HTML ceaedabb_oldboy.html mv chfdfjea_oldgirl.HTML chfdfjea_oldboy.html mv dabjbdjb_oldgirl.HTML dabjbdjb_oldboy.html mv efbfaagg_oldgirl.HTML efbfaagg_oldboy.html mv eifdabhe_oldgirl.HTML eifdabhe_oldboy.html mv fdgfbffe_oldgirl.HTML fdgfbffe_oldboy.html mv fffffccf_oldgirl.HTML fffffccf_oldboy.html [root@nfs_server test]# ls|awk -F '_' '{print "mv " $0,$1"_oldboy.html"}'|bash [root@nfs_server test]# ls acjfghda_oldboy.html dabjbdjb_oldboy.html adcbajjf_oldboy.html efbfaagg_oldboy.html aifdadai_oldboy.html eifdabhe_oldboy.html ceaedabb_oldboy.html fdgfbffe_oldboy.html chfdfjea_oldboy.html fffffccf_oldboy.html [root@nfs_server test]# rename "oldboy.html" "oldgirl.HTML" *.html [root@nfs_server test]# ls acjfghda_oldgirl.HTML dabjbdjb_oldgirl.HTML adcbajjf_oldgirl.HTML efbfaagg_oldgirl.HTML aifdadai_oldgirl.HTML eifdabhe_oldgirl.HTML ceaedabb_oldgirl.HTML fdgfbffe_oldgirl.HTML chfdfjea_oldgirl.HTML fffffccf_oldgirl.HTML
答案二、
[root@nfs_server scripts]# cat shell3.sh #!/bin/bash cd /root/clc/test for n in `ls` do cd /root/clc/test mv "$n" `echo $n|sed 's#oldboy.html#oldgirl.HTML#g'` #sed -i 's#oldboy.html#oldgirl.HTML#g' /root/clc/test/$n done [root@nfs_server scripts]#
原文链接:20道shell题目第2题(随机数有关)和第3题,这两题是相关的。,转载请注明来源!