当前位置:编程学习 > 网站相关 >>

shell脚本随机输出一个文件的25行

前言
好久没写shell脚本了,今天看到群里有这么一个需求,截图如下:

 \
 

 


我也是复习一下shell脚本,就顺手写了个程序测试了一下,基本上通过了


思路
首先,用shell脚本按行读取文本,将每一行存入一个数组中
每次选择一个随机数,来从数组中取数据
注意,不能是重复的行,所以随机数有标记字段


Shell脚本
[html]
#!/bin/bash 
 
#文件位置 
file="./test.txt" 
#计数器 
i=0 
 
#按行读取文件内容,存入arr数组中 
for line in $(awk '{print $0}' $file) 
do 
    arr[$i]=$line 
    i=$(expr $i + 1) 
done 
 
#构造随机数数组,假定文件只有100行,当random[i]=0时说明第i行没有被读取 
for i in $(seq 1 100) 
do 
    random[$i]=0 
done 
 
#构造随机数,随机选取25行 
for ((i=0; i<25;)) 
do 
    index=$RANDOM%100 
    if [ ${random[$index]} -eq 0 ]; then 
        random[$index]=1 
        echo ${arr[$index]} 
        i=$(expr $i + 1) 
    fi 
done 

#!/bin/bash

#文件位置
file="./test.txt"
#计数器
i=0

#按行读取文件内容,存入arr数组中
for line in $(awk '{print $0}' $file)
do
 arr[$i]=$line
 i=$(expr $i + 1)
done

#构造随机数数组,假定文件只有100行,当random[i]=0时说明第i行没有被读取
for i in $(seq 1 100)
do
 random[$i]=0
done

#构造随机数,随机选取25行
for ((i=0; i<25;))
do
 index=$RANDOM%100
 if [ ${random[$index]} -eq 0 ]; then
  random[$index]=1
  echo ${arr[$index]}
  i=$(expr $i + 1)
 fi
done

 

补充:综合编程 , 其他综合 ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,