AWK操作字符串的截取

对于awk和Bash来说,他们使用的是不同的string索引系统;

bash的第一个字符从0开始记录;

awk的第一个字符从1开始记录;

#012345678   ------------Bash

#123456789  -------------Awk

以下是案例说明:

[root@Slave02 shell]# vi substring-extraction.sh
#!/bin/bash

String=23skidoo1

echo ${String:2:4}
echo |awk '{ print substr("'"${String}"'",3,4) }'

exit 0
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
"substring-extraction.sh" [New] 8L, 108C written
[root@Slave02 shell]# sh substring-extraction.sh 
skid
skid
[root@Slave02 shell]#

使用变量的前缀来匹配前面声明过的所有变量;

如:

[root@Slave02 shell]# xyz23=watever
[root@Slave02 shell]# xyz24=asdf
[root@Slave02 shell]# echo "
a=${!xyz*}"
a=xyz23 xyz24
[root@Slave02 shell]# echo "a=${!xyz@}"
a=xyz23 xyz24
[root@Slave02 shell]# 

抛骰子游戏;

SPOTS=6      -----取模为6,范围在0-5
die1=0
die2=0
 

------------2个变量名称,保证每个平面选择的数字记录相同


let "die1 = $RANDOM % $SPOTS +1"
let "die2 = $RANDOM % $SPOTS +1"

let "throw = $die1 + $die2"

echo "Throw of the dice = $throw"
echo

exit 0

以下验证结果:

Random number greater than 200 --- 25552

Throw of the dice = 5

[root@Slave02 shell]# 

random number less than 500 --- 0

Random number greater than 200 --- 9765

Throw of the dice = 2

[root@Slave02 shell]# 
Random number greater than 200 --- 31180

Throw of the dice = 10

[root@Slave02 shell]# 

[root@Slave02 shell]# sh random2.sh 
Random number between 0 and 1 = 0.246062
[root@Slave02 shell]# sh random2.sh 
Random number between 0 and 1 = 0.619153
[root@Slave02 shell]# sh random2.sh 
Random number between 0 and 1 = 0.619153
[root@Slave02 shell]# sh random2.sh 
Random number between 0 and 1 = 0.619153
[root@Slave02 shell]# sh random2.sh 
Random number between 0 and 1 = 0.619153
[root@Slave02 shell]# sh random2.sh 
Random number between 0 and 1 = 0.201116
[root@Slave02 shell]# cat random2.sh 
#!/bin/bash


AWKSCRIPT='{ srand(); print rand() }'    -srand中伪随机的计算


echo -n "Random number between 0 and 1 = "
echo | awk "$AWKSCRIPT"




exit 0
[root@Slave02 shell]#


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值