Putorius
Linux Quick Tips

How to Get File Name Only With Linux Find Command

The Linux find command is a powerful tool with many options. However, the output always displays the full path of the file. Sometimes it is desirable to only get the filename itself. In this Linux quick tip we will discuss some methods for formatting the output to show the file name only.

Let's take a look at an example of find output. Here we are searching for a song named Mother in the Music directory.

[mcherisi@putor ~]$ find ~/Music -name Mother
/home/mcherisi/Music/Pink_Floyd/Mother

As you can see, it found the file and returned the full path. But, what if we only wanted the file name itself? Well as with anything in Linux you have a few (actually many) options. Let's examine just a few.

Strip The Directory Information From Output with Basename

The first thing that comes to my mind is the basename command. This shell utility is designed specifically to remove the path from a file name. In the following example we will use command substitution to pass the output of the find command to basename.

[mcherisi@putor ~]$ basename -a $(find ~/Music -name Mother)
Mother

In the above example we used basename with the -a option. This ensures that all results are displayed if multiple files are found.

NOTE: For more information on the basename command read "Linux Basename Command - Strip Directory from Filename and more".

Instead of using command substitution, we can also use basename with -exec.

[mcherisi@putor ~]$ find ~/Music -name "M*" -exec basename {} \;
Music
Mother
Mean_Street

Using Printf to Format the Output of Find Command

Another option is to use find's built in -printf option. Here we are using the %f format specifier followed by \n (newline).

[mcherisi@putor ~]$ find ~/Music -name Mother -printf "%f\n"
Mother

For more information about the find command, read our primer called "Linux Find Command - Search for Files on the Linux Command Line"

Exit mobile version