linux 脚本输入变量,awk的SHELL脚本变量输入方式(SHELL参数传递、标准输入/键入)的区别&深入理解BEGIN...

生成随机数脚本

需求:从一个范围的整理内,随机生成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的理解)

阅读(367) | 评论(0) | 转发(0) |

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值