• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer navigation

The Geek Diary

  • OS
    • Linux
    • CentOS/RHEL
    • VCS
  • Interview Questions
  • Database
    • MariaDB
  • DevOps
    • Docker
    • Shell Scripting
  • Big Data
    • Hadoop
    • Cloudera
    • Hortonworks HDP

A little trick: select a random file or line in the file with shuf

by admin

Of course, we all value freedom forever. In particular, freedom of choice. But sometimes it is burdensome. He looked, for example, in the folder with the video, and there are a bunch of films from the untreated. What to stop on, what to choose? What a nuisance! I just want to get a coin and, by a simple coincidence, “heads-tails” solve the problem, but, alas, oh, can’t find a coin from 20-30-40- ?? by the parties. Fortunately, there is such a coin in Linux. Who cares – under cat.

You do not need to install anything. Everything is already in any Linux distribution. This is the shuf command, a random value generator. You can fully familiarize yourself with its functionality by typing “man shuf”, but I will talk about two specific examples.

So, we return to our folder with movies (“cd / home / user / video”, for example) and enter the following:

$ ls | shuf -n1

The first part should already be familiar to everyone, the ls command gives us the contents of the folder. Next, we pipe the output of the ls command to the shuf command, which randomly selects one line from this output. That is one file from the entire contents of the folder (or rather, its name). Random. Do you want not one, but a couple or more? Ok, instead of “-n1” write “-n2” or “-n3” or another value.

Second example. We have a list of something in stock. It is located in a plain text file. We type in the console:

$ cat spisok.txt | shuf -n1

All the same, only instead of the folder, e have a text file. The cat command outputs the contents of the file to the terminal, and the shuf command selects a random string from this content. That’s all. Obviously, you can come up with other use cases.

Filed Under: Linux

Some more articles you might also be interested in …

  1. dd: command not found
  2. minikube Command Examples
  3. minetest Command Examples
  4. amixer Command Examples in Linux
  5. datamash Command Examples in Linux
  6. pvcreate Command Examples in Linux
  7. “hg server” Command Examples
  8. ceph Command Examples in Linux
  9. How to configure xhost to be persistent across reboots in Linux
  10. find Command Examples in Linux

You May Also Like

Primary Sidebar

Recent Posts

  • Vanilla OS 2 Released: A New Era for Linux Enthusiasts
  • mk Command Examples
  • mixxx Command Examples
  • mix Command Examples

© 2025 · The Geek Diary

  • Archives
  • Contact Us
  • Copyright