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