How to exclude directories when getting list in Linux

Default featured post

In Linux terminal when you use ls command it returns list of all files and directories and unfortunately there is no option available to exclude either files or directories. Therefore, ls command cannot be used for this purpose but luckily there is a replacement command for this purpose and that command is find. The aim of this post is not to describe about this command but the aim is to show how to get list of files only in Linux terminal. For reaching the purpose you can use the find command like following example,

$ find . -type f -maxdepth 1

Type parameter indicates that only return the list of entities which are files and maxdepth parameter demonstrates the depth for the search, 1 means the current folder without sub directories. If you put 2 instead of one, find command searches the current directory with its sub directories and if you put 3 sub-directories of the main sub-directories will be scanned as well. It exactly looks like Tree in data structure. In other word, the number in front of maxdepth demonstrates the hierarchy of the directory. The only issue of the above command is that, it returns list of hidden files as well. Now if you want to get list of files excluding directories and hidden files you should use find command like below,

$ find . -type f -maxdepth 1 \( ! -iname && \)

The only difference is the second part that demonstrates NOT (with ! sign) to list files that start with . sign.

Now the only remain question is why we should list only files and exclude directories. In fact the answer of this question is mostly depends on the situation but in my case I wanted to create playlist of my audio files in a directory which contains many sub-directories as well. In addition to that I want to add name of the files in reverse sorted form (from Z to A) and therefore, I piped the output to sort command. My final command was something like below,

$ find . -type f -maxdepth 1 | sort -r > Myplaylist.m3u

For more information about find command please refer to online man page of the command in below link.