如何从shell中的文本文件中选择随机的唯一行?
发布时间:2020-12-16 01:29:21 所属栏目:安全 来源:网络整理
导读:我有一个不明行数的文本文件.我需要随意抓取一些这些行,但我不希望有任何重复的风险. 我试过这个: jot -r 3 1 `wc -linput.txt` | while read n; do awk -v n=$n 'NR==n' input.txtdone 但这是丑陋的,不能防止重复. 我也试过这个: awk -vmax=3 'rand() 0.5
我有一个不明行数的文本文件.我需要随意抓取一些这些行,但我不希望有任何重复的风险.
我试过这个: jot -r 3 1 `wc -l<input.txt` | while read n; do awk -v n=$n 'NR==n' input.txt done 但这是丑陋的,不能防止重复. 我也试过这个: awk -vmax=3 'rand() > 0.5 {print;count++} count>max {exit}' input.txt 但这显然也不是正确的方法,因为我不能保证甚至获得最大的线. 我被卡住了我该怎么做?
如果jot在你的系统上,那么我猜你运行的是FreeBSD或者OSX而不是Linux,所以你可能没有rl或sort-r这样的工具.
别担心.以前我不得不这样做.改为: [ghoti@pc ~]$cat rndlines #!/bin/sh # default to 3 lines of output lines="${1:-3}" # First,put a random number at the begginning of each line. while read line; do echo "`jot -r 1 1 1000000` $line" done < input.txt > stage1.txt # Next,sort by the random number. sort -n stage1.txt > stage2.txt # Last,remove the number from the start of each line. sed -r 's/^[0-9]+ //' stage2.txt > stage3.txt # Show our output head -n "$lines" stage3.txt # Clean up rm stage1.txt stage2.txt stage3.txt [ghoti@pc ~]$./rndlines input.txt two one five [ghoti@pc ~]$./rndlines input.txt four two three [ghoti@pc ~]$ 我的input.txt有五行,带有数字. 我已经拼写出来,以便于阅读,但在现实生活中,您可以将东西组合成长管道,您将需要清理可能创建的任何(唯一命名的)临时文件. 这是一个1行的示例,它也使用awk更简洁地插入随机数: $printf 'onentwonthreenfournfiven' | awk 'BEGIN{srand()} {printf("%.20f %sn",rand(),$0)}' | sort | head -n 3 | cut -d -f2- 请注意,较旧版本的sed(在FreeBSD和OSX中)可能需要使用-E选项而不是-r来处理ERE或BRE方言. (当然,你可以在BRE中表达,但为什么?)(古代版本的sed(HP / UX等)可能需要BRE,但如果您已经知道如何执行此操作,则只能使用它们). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |