這次給大家?guī)淼氖莝huf 命令教程,shuf 命令用于在類 Unix 操作系統(tǒng)中生成隨機(jī)排列。使用 shuf 命令,我們可以隨機(jī)打亂給定輸入文件的行。shuf 命令是 GNU Coreutils 的一部分,因此你不必?fù)?dān)心安裝問題。在這個(gè)簡短的教程中,讓我向你展示一些 shuf 命令的例子。
帶例子的 shuf 命令教程
我有一個(gè)名為 ostechnix.txt 的文件,內(nèi)容如下:
$ cat ostechnix.txt line1 line2 line3 line4 line5 line6 line7 line8 line9 line10
現(xiàn)在讓我們以隨機(jī)順序顯示上面的行。為此,請(qǐng)運(yùn)行:
$ shuf ostechnix.txt line2 line8 line5 line10 line7 line1 line4 line6 line9 line3
看到了嗎?上面的命令將名為 ostechnix.txt 中的行隨機(jī)排列并輸出了結(jié)果。
你可能想將輸出寫入另一個(gè)文件。例如,我想將輸出保存到 output.txt 中。為此,請(qǐng)先創(chuàng)建 output.txt:
$ touch output.txt
然后,像下面使用 -o 標(biāo)志將輸出寫入該文件:
$ shuf ostechnix.txt -o output.txt
上面的命令將隨機(jī)隨機(jī)打亂 ostechnix.txt 的內(nèi)容并將輸出寫入 output.txt。你可以使用命令查看 output.txt 的內(nèi)容:
$ cat output.txt line2 line8 line9 line10 line1 line3 line7 line6 line4 line5
我只想顯示文件中的任意一行。我該怎么做?很簡單!
$ shuf -n 1 ostechnix.txt line6
同樣,我們可以選擇前 “n” 個(gè)隨機(jī)條目。以下命令將只顯示前五個(gè)隨機(jī)條目:
$ shuf -n 5 ostechnix.txt line10 line4 line5 line9 line3
如下所示,我們可以直接使用 -e 標(biāo)志傳入輸入,而不是從文件中讀取行:
$ shuf -e line1 line2 line3 line4 line5 line1 line3 line5 line4 line2
你也可以傳入數(shù)字:
$ shuf -e 1 2 3 4 5
要快速在給定范圍選擇一個(gè),請(qǐng)改用此命令:
$ shuf -n 1 -e 1 2 3 4 5
或者,選擇下面的任意三個(gè)隨機(jī)數(shù)字:
$ shuf -n 3 -e 1 2 3 4 5
我們也可以在特定范圍內(nèi)生成隨機(jī)數(shù)。例如,要顯示 1 到 10 之間的隨機(jī)數(shù),只需使用:
$ shuf -i 1-10
有關(guān)更多詳細(xì)信息,請(qǐng)參閱手冊(cè)頁。
$ man shuf想要學(xué)習(xí)更多的IT技能那就加入我們吧,粵嵌科技創(chuàng)始于2005年,擁有“牛”全面的IT師資教育團(tuán)隊(duì)和“新”全的IT培訓(xùn)課程體系,只為了打造“牛”的你。歡迎咨詢