user
How to list only files with ls ?
alphonsio

To list only files (and not directories) using the ls command in a Unix-like system (such as Linux or macOS), you can use the following approaches:

Using ls and grep

You can combine ls with grep to filter out directories:

ls -p | grep -v /
  • ls -p appends a slash (/) to directories.
  • grep -v / filters out lines containing /, effectively removing directories from the list.

Using find

You can use the find command to list only files:

find . -maxdepth 1 -type f
  • find . starts the search in the current directory.
  • -maxdepth 1 limits the search to the current directory (i.e., it doesn't recurse into subdirectories).
  • -type f limits the results to regular files.

Using ls and awk

Another method is to use ls in combination with awk:

ls -l | awk '$1 !~ /^d/'
  • ls -l provides detailed listing of files and directories.
  • awk '$1 !~ /^d/' filters out lines where the first character (which indicates file type) is d, meaning directory.

Using ls and find in combination with xargs

You can also use find to identify files and then list them using ls:

find . -maxdepth 1 -type f -print0 | xargs -0 ls -l
  • find . -maxdepth 1 -type f -print0 finds files in the current directory and uses a null character to separate them.
  • xargs -0 ls -l takes the null-separated list of files and runs ls -l on them.

Using ls and stat

You can use stat to filter only regular files:

ls -1 | xargs -I {} stat -c '%F %n' {} | grep 'regular empty file' | awk '{print $4}'
  • ls -1 lists files and directories one per line.
  • xargs -I {} stat -c '%F %n' {} runs stat on each item to get the file type and name.
  • grep 'regular empty file' filters for regular files (the string may change according to your system)
  • awk '{print $4}' prints only the file names.

Example

If you have the following files and directories:

$ ls -l
total 8
-rw-r--r-- 1 user user 0 Jun 25 10:00 file1
-rw-r--r-- 1 user user 0 Jun 25 10:00 file2
drwxr-xr-x 2 user user 4096 Jun 25 10:00 dir1
drwxr-xr-x 2 user user 4096 Jun 25 10:00 dir2

Here is the output of the above methods :

$ ls -p | grep -v /
file1
file2
$ find . -maxdepth 1 -type f
./file1
./file2
$ ls -l | awk '$1 !~ /^d/'
total 8
-rw-r--r-- 1 webmaster webmaster    0 Jun 26 18:31 file1
-rw-r--r-- 1 webmaster webmaster    0 Jun 26 18:31 file2
$ find . -maxdepth 1 -type f -print0 | xargs -0 ls -l
-rw-r--r-- 1 webmaster webmaster 0 Jun 26 18:31 ./file1
-rw-r--r-- 1 webmaster webmaster 0 Jun 26 18:31 ./file2
$ ls -1 | xargs -I {} stat -c '%F %n' {} | grep 'regular empty file' | awk '{print $4}'
file1
file2

These approaches help ensure that you list only files and not directories.