Chinaunix首页 | 论坛 | 博客
  • 博客访问: 45558
  • 博文数量: 14
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 150
  • 用 户 组: 普通用户
  • 注册时间: 2015-11-16 18:43
文章分类

全部博文(14)

文章存档

2016年(6)

2015年(8)

我的朋友

分类: LINUX

2015-11-20 20:08:38

生成随机数脚本 
需求:从一个范围的整理内,随机生成X个随机数

(一)直接使用SHELL参数输入
awk -v NUM=$1 -v MAX=$2 ' #输入SHELL的参数到变量
  BEGIN {
                    if ( NUM <= 0 )
                        NUM = 6
                    if ( MAX <= 0 )
                        MAX = 30
                   srand()
                   for ( i=1 ; i<=NUM ; i++ ) {
                         do{
                                   select = 1 + int(MAX * rand())
                          } while ( select in select_num )
                   select_num[i]=select
                   print select_num[i]
                    }
                   exit
            }'    #因为没有输入文件,需在输入之前执行脚本,所以脚本需要在BEGIN之内,注意大括号对齐


执行:
 [root@czw unit9]# ./awkscript1_lotto 5 10  #直接作为shell程序的参数输入
3
7
3
7
6


 (二)标准输入作为awk的输入
awk '
    BEGIN {
                printf ( "please input the random number count in the range of the topnumber .\n")
                printf ( "count and topnumber : ")
              }    #变量从标准输入输入,所以BEGIN只需打印提示符,注意大括号范围
    {
        NUM = $1
        MAX = $2
        if ( NUM <= 0 )
                NUM = 6
        if ( MAX <= 0 )
                MAX = 30
        srand()
        for ( i=1 ; i<=NUM ; i++ ) {
            do{
                    select = 1 + int(MAX * rand())
            } while ( select in select_num )
        select_num[i]=select
        print select_num[i]
           }
    exit
    }' -


执行:
[root@czw unit9]# ./awkscript1_lotto
please input the random number count in the range of the topnumber .
input count and topnumber : 5 10
4
7
6
5
6

总结:
注意变量输入的方式,导致awk脚本中BEGIN的范围(加深对BEGIN的理解)


 
阅读(983) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~