- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What's the difference between nohup and ampersand (&) on Linux?
Linux provides us with different utility commands that we can make use of to print a random line from any files in the Unix command line. Mostly we make use of either the shuf command or the sort command, and in this article I’ll explain both the commands and which one is better and why.
Shuf Command
The shuf command in Linux is used to write random permutations of the input lines to the standard output. The idea of randomizing the input is the same as one does when the cards are shuffled. On most of the Linux operating systems it is present by default, as it is part of the GNU Coreutils and in case of the BSD like Mac OS X, we need to explicitly install the Coreutils first, then we can make use of it.
Syntax
shuf [OPTION] [FILE]
On Mac OS X, the syntax looks something like this −
gshuf [OPTION] [FILE]
The most basic case of making use of the shuf command is to use it without any options and file.
Example
Consider the example shown below −
immukul@192 d1 % gshuf apple sample orange
Now press CTRL+D and you will get the inputs you entered in a random order printed to the screen.
Output
sample apple orange
Now let’s make use of the shuf/gshuf command to print a random line from a .txt file.
Consider the example shown below
Example
gshuf -n 1 file.txt
Output
unsalutary
If I run the same command again, we will get a different output.
Output
typhlopexia
Sort Command
The sort command in Linux is used to sort the contents of a file and we can use the head command along with the sort command to get a random line from a .txt file.
Consider the example shown below −
Example
sort --random-sort file.txt | head -n 1
Output
podiatry
It should be noted that it is better to make use of the gshuf command as the sort command usually takes more time.