iT邦幫忙

6

亂數或隨機取樣的工具:shuf

在程式語言環境裡,常有取亂數的需要。而在 shell 的環境下有 shuf 的工具,省去寫程式的步驟,只要加參數即可運作。
亂數排序檔案
Linux 裡常會附有字典檔,主要是做為檢測密碼是否符合某字用,如果要隨機選幾個單字,shuf即會把整個檔案各行的順序打亂秀出,但整個檔案有5萬多行,只要秀五個,加-n的參數來取指定數目的單字。

[singernew@ithelp ~]$ shuf /usr/share/dict/cracklib-small -n 5
charleston
reassures
troublemaker's
definition
warred
[singernew@ithelp ~]$ shuf /usr/share/dict/cracklib-small -n 5
transcript's
sri
tweeze
snaring
audiologists

給一定範圍的數字亂數排序
用 -i 的參數指定亂排範圍內的數字。

[singernew@ithelp ~]$ shuf -i 20-222 -n 5
193
85
160
81
151
[singernew@ithelp ~]$ shuf -i 20-222 -n 5
49
158
72
66
108

給一定的參數,亂排這些參數
用 -e 為參數,會 echo 後面所接的參數以亂數排序

[singernew@ithelp ~]$ shuf -e iT 邦 幫 忙
忙
幫
邦
iT
[singernew@ithelp ~]$ shuf -e iT 邦 幫 忙
iT
忙
幫
邦
[singernew@ithelp ~]$ shuf -e iT 邦 幫 忙
忙
邦
幫
iT
[singernew@ithelp ~]$ shuf -e iT 邦 幫 忙
iT
幫
邦
忙

若希望亂排的結果都在同一行,可加 -z 參數

[singernew@ithelp ~]$ shuf -z -e iT 邦 幫 忙
邦忙幫iT[singernew@ithelp ~]$

與 sort -R的效能比較
sort 的工具可用 -R 的參數,做到亂數排序的功能,但從下面的執行速度就可看出,需要用亂數排序時,shuf是比較好的選擇。

[singernew@ithelp ~]$ time sort -R < /usr/share/dict/cracklib-small > /dev/null

real    0m0.247s
user    0m0.247s
sys     0m0.000s
[singernew@ithelp ~]$ time shuf /usr/share/dict/cracklib-small > /dev/null

real    0m0.008s
user    0m0.003s
sys     0m0.003s

參考資源:
http://www.whiteboardcoder.com/2013/03/linux-shuf-command.html
http://tuxthink.blogspot.tw/2012/06/shuf-to-shuffle-contents-of-file.html


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
gholk
iT邦新手 5 級 ‧ 2020-12-03 18:18:54

shuf 的 -z 選項不是把輸出擠在同一行,是把分隔符從 \n 改成 null \0 ,終端機不會顯示 null ,所以看起來就像沒有分隔符。用 shuf -z -e iT 邦 幫 忙 | xxd| less 就可以看到個每字中間有 null 。

如果需要擠在同一行,可以用 shuf -e iT 邦 幫 忙 | tr -d '\n'

我要留言

立即登入留言