本文介绍采用Linux脚本,批量自动生成文件名随机的html文件,要满足的要求如下:

1.批量自动生成100个html文件;

2.文件名包含8个随机英文小写字母和2个随机0~9的数字;

思路分析:

要求1:利用脚本的for循环语句,结合touch命令,批量生成要求数量的文件;

要求2:文件名中要求的小写字母和数字数量确定,需要使用openssl命令,并结合cut命令.具体内容如下:

生成45个随机数的openssl命令:

1
openssl rand -base64 45    (1)

在命令(1)的基础上,分别将其中的非小写英文字母和非数字替换掉,就可以获得纯英文字母的字符串(命令2)和纯数字的字符串(命令3):

1
2
openssl rand -base64 45 | sed 's#\[^a-z\]##g'  (2)
openssl rand -base64 45 | sed 's#\[^0-9\]##g'  (3)

采用cut命令可以截取字符串:

1
2
openssl rand -base64 45 | sed 's#\[^a-z\]##g'  |  cut -c 2-9   (4)
openssl rand -base64 45 | sed 's#\[^0-9\]##g'  |  cut -c 2-3   (5)

其中命令(4)获取8个随机小写英文字符, 命令(5)获取2个随机数字,再将两者拼合生成文件名.

脚本源代码及效果:

1
2
3
4
5
6
7
8
9
10
11
#!/bin/bash
mydir=./files
[-d "$mydir" ] || mkdir -p $mydir

for n in `seq 100`
do
  head=`openssl rand -base64 45 | sed 's#\[^a-z\]##g'  |  cut -c 2-9`
    tail=`openssl rand -base64 45 | sed 's#\[^0-9\]##g'  |  cut -c 2-3`
    name=$head$tail
    touch $mydir/${name}.html
done

运行上述脚本:./mkhtml.sh, 执行效果如下:

图1 脚本生成的批量html文件

注意点:

1.语句”head=”和”tail=”两条语句的右边需要符号”`“包括;

2.linux shell脚本中拼合字符串, 直接拼合,不需要”+”号;