by Ray Bayley

Infrequently Asked Questions: ls and find

News
Nov 3, 20063 mins

I have a number of MP3 files in a folder. How can I create a file which lists the names of the MP3 files?

I have a number of MP3 files in a folder. How can I create a file which lists the names of the MP3 files?

–Lonecrow

This is not something which is limited to MP3 files, of course. It can be useful for any folder with filenames of any type.

Lonecrow started out well, he used the ls command to list the contents of the “music” folder

     ls music > mp3list.txt


but this command only listed the contents of the main folder, it didn’t list the contents of any sub-folders. Here is where the man pages come in useful.

The man page for ls (man ls) lists all of the available switches for the command. Reading through the options, we come to

-R, –recursive

list subdirectories recursively

This will also list out the contents of any subdirectories.

And, to complete this solution, the > mp3list.txt outputs the results into the mp3list.txt text file.

While ls is suited to simpler searches and search/outputs, Linux has another, more powerful, way of doing this. The find command is installed on every Linux system by default and is ready to be used. As ever, the man page should be read through to discover the many ways that this command works (man find).

Briefly, to show this in the context of this problem, the following command would do much the same thing:

find /path/to/music/ *.* -type f -fprint mp3list.txt

The difference in the two commands is simple – the first will output exactly what is in the “music” folder. If there are subdirectories in that folder, the subdirectories will be listed but the contents of the folders will not. In the second example, the output file will show the contents of all subdirectories, listed in directory order. e.g /path/to/music/mp3folder1/mp31.mp3, /path/to/music/mp3folder2/mp32.mp3 and so on.

The second command says to find all the files in the directory “music” of the type “regular files” (-type f) and output them to mp3list.txt (-fprint mp3list.txt).

Without knowing the directory structure of Lonecrow’s Music folder I can’t say which solution is the best fit for his problem. However, again we see that Linux can give you more than one solution for even the most basic of problems and it is up to the user themselves as to which one to choose.

Ray Bayley (XavierP)