4 Easy Ways to Count Files in Linux Using CLI

Written by

Reviewed by

Last updated: July 24, 2024

Expert verified

SVG Image

TL; DR

To count files in Linux using the command line, you can try the following ways:

  1. ls Command: Use ls | wc -l to list and count all files and directories in the current directory.
  2. Using du and awk: Combine du -a | awk ‘{print $1}’ | wc -l to list and count all files and directories, or use find . -type f -exec du -a {} + | awk ‘{print $1}’ | wc -l to count only files.
  3. Tree Command: Use tree to display and count all files and subdirectories in a hierarchical tree format.

Read the article to know more about how to count files in Linux with step-by-step methods and effective file-counting tips.

Keeping track of file counts for various tasks can be a bit overwhelming. In this post, I’ll guide you through straightforward solutions for counting files. You’ll learn both command-line and graphical methods, ensuring you find a technique that suits your needs. I’ll cover basic commands like ls and find, advanced methods using du and awk, and graphical tools for a visual approach. Let’s explore and make your file management process efficient and effective.

Common Use Cases for Counting Files

Counting files in Linux is a useful task in many situations. Here are some common use cases:

  • System Administration: System administrators often need to count files to manage storage, monitor file usage, and ensure the system runs smoothly. For example, they might check how many log files are in a directory to prevent storage from filling up.
  • Development: Developers might count files to understand the size of a project, check how many source code files are in a directory, or ensure that all expected files are present after a build process.
  • Backup Management: When managing backups, it’s important to count files to verify that all files have been backed up correctly. This ensures no data is missing.
  • Performance Monitoring: Sometimes, counting files helps in monitoring performance. If a directory has too many files, it can slow down the system. Knowing the file count helps in optimizing performance.
  • File Organization: Organizing files can be easier when you know how many files you are dealing with. It helps in creating subdirectories and categorizing files efficiently.

How to Count Files in Linux

To count files in Linux, you can use several methods depending on your preference. Use ls | wc -l to list and count files in the current directory, or try find . -type f | wc -l to count all files, including subdirectories.

For a visual approach, use the tree command, which displays and counts files in a hierarchical format. If you prefer a graphical method, open your file manager, right-click the directory, select Properties, and view the file count there.

Let’s learn each of these methods in detail to count files in Linux here:

1. ls Command

The most basic method for counting files in Linux is to use the ls command. This command lists the files in a directory and provides information on each file, including its size, permissions, and ownership. Here are detailed steps to use this command to count files in Linux using CLI:

  1. Navigate to the directory using the cd command.
navigate to the directory
  1. To count the number of files in a directory using ls, you can use the following command:
ls | wc -l
  1. The command ls | wc -l lists all the files and directories in the current directory and pipes the output to the wc -l command, which counts the number of lines in the output. This will give you the total number of files and directories in the current directory, including any subdirectories.
lists all the files in the current directory

2. Using du and awk

This method uses the du (disk usage) command combined with awk to provide a flexible way to count files, especially useful for advanced counting and filtering tasks.

  1. Open your Terminal window.
  2. Run the following command to count all files and directories:
du -a | awk '{print $1}' | wc -l

This command lists all files and directories, uses awk to print each file’s size, and wc -l to count the lines.

counting files and directories using du and awk
  1. To count only the files and exclude directories, use:
find . -type f -print | wc -l
counting only files using find
  1. Alternatively, combine find with awk:
find . -type f -exec du -a {} + | awk '{print $1}' | wc -l

This command counts only the files and skips directories.

counting only files using find and awk

3. Tree Command

The tree command is a recursive directory listing command that displays the contents of a directory and its subdirectories in a tree-like format. Here’s how you can use this command to count files in Linux:

  1. In the Linux command prompt, navigate to the directory using the cd command.
linux command to navigate to the directory
  1. Execute the tree command in the Terminal window, just as written below:
tree
  1. It will display the directory tree structure starting from the specified directory. As you can see, the output shows all the subdirectories and files within the specified directory and its subdirectories in a hierarchical tree-like format. Additionally, it’ll display the total files counted in the directory.
tree structure from the specified directory
  1. Alternatively, you can use the tree command just with the directory path for counting files in a directory.
tree directorypath
  1. You’ll notice it has the same output as the one executed in earlier steps.
tree command with the directory path

4. Counting Files Using a GUI Method

For users who prefer a graphical interface, using a file manager provides a visual way to count files without using the terminal.

  1. Open Nautilus, you can find Nautilus (Files) in your applications menu.
opening file manager
  1. Go to the directory where you want to count the files.
navigating to directory in file manager
  1. Right-click inside the directory and select Properties.
selecting properties option to view files count
  1. The properties window will show the total number of files and subdirectories.
viewing files count through gui

Advanced Methods for Counting Files in a Directory

1. Directory Depth Count Command

Another basic command to count files in Linux is the find command. This command searches for files in a directory hierarchy and can be used to count the number of files in a directory. Here’s how you can use implement this method:

  1. To count the number of files in a directory using find, you can use the following command:
find . -maxdepth 1 -type f | wc -l

This command find . -maxdepth 1 -type f | wc -l uses the find command to search for all files in the current directory (specified by the “.“), but limits the search to a maximum depth of 1 (only files in the current directory, not in any subdirectories) and only consider files (not directories or other types of files).

    The output is then piped to the wc -l command to count the number of lines in the output and give you the total number of files in the current directory only.

      command to search for all files

      2. Files Count with Specific Criteria

      If you need to count files in Linux with specific criteria, such as by file type or modification date, you can use the ls command line options with flags or options to specify criteria for file counting. To do so, follow these steps:

      1. To count only .txt files in a directory, you can use the following command:
      ls *.txt | wc -l
      1. This command uses the wildcard character * to match all files with a .txt extension and wc to count the number of lines in the output.
      command to count files in linux with specific criteria

      3. Automate File Count Tasks

      To streamline and automate counting files in Linux, create a shell script that executes the required commands and generates the desired output. Follow the step-by-step guide below to simplify the process:

      1. To count the number of files in the /home/user/Documents directory, create a script with the following code :
      #!/bin/bash
      cd /home/user/Documents
      ls | wc -l
      1. To execute the script, you can save it to a file with a .sh extension, like count_files.sh. Then, make it executable using the chmod command. Your command should look like this:
      chmod +x count_files.sh
      1. Then, run this file using the following command in the Terminal app.
      ./count_files.sh
      1. Once done, this script will count files and return the following output:
      to execute the script

      4. View and Count Files in a Hierarchical Format

      The tree command is a recursive directory listing command that displays the contents of a directory and its subdirectories in a tree-like format. Here’s how you can use this command to count files in Linux:

      1. In the Linux command prompt, navigate to the directory using the cd command.
      linux command to navigate to the directory
      1. Execute the tree command in the Terminal window, just as written below:
      tree
      1. It will display the directory tree structure starting from the specified directory. As you can see, the output shows all the subdirectories and files within the specified directory and its subdirectories in a hierarchical tree-like format. Additionally, it’ll display the total files counted in the directory.
      tree structure from the specified directory
      1. Alternatively, you can use the tree command just with the directory path for counting files in a directory.
      tree directorypath
      1. You’ll notice it has the same output as the one executed in earlier steps.
      tree command with the directory path

      4 Quick Tips to Count Files in Linux

      To count files in Linux more efficiently and optimize your overall file management workflow, try these four practical tips:

      1. Add Wildcards to the ls Command

      Wildcards feature in Linux, represented by an asterisk (*), serves as a powerful tool in file search and organization. It allows you to match multiple files based on your desired criteria. That is, you can use wildcards to find files in Linux that match specific patterns or even extensions. Here’s what your command should look like:

      ls *.txt

      By executing this command, you can locate and display all files that have a .txt extension in a directory. In this way, you can quickly and efficiently search and organize files on your Linux system.

      match files with specific extensions

      2. Run tee and ls Commands

      The tee command is a useful utility that allows you to redirect the output of a command to multiple destinations simultaneously. It is particularly handy when you want to both view the output on your screen and store it in a file.

      This ensures that you have a permanent record of the directory’s contents, which can be useful for later analysis, reference, or sharing with others. To use this command, execute the following command line in the Linux command prompt:

      ls | tee file_list.txt

      When this command is executed, the output of the ls command is passed as input to tee. The tee command, in turn, creates two streams: one stream sends the output to the screen (standard output), and the other stream saves it to the specified file (file_list.txt) in the current directory. As a result, you will be able to observe the directory listing displayed on your screen and saved in the text file.

      saves them to a file named file list txt

      3. Use File Properties to Count Files

      In Linux, you can use the graphical interface, which offers a more user-friendly approach to viewing the total number of files in a directory. In this way, it enables you to have easy access to file properties and provides a quick view of the directory’s contents. This method is ideal for users who prefer visual tools over command-line operations.

      To count files using this method, simply right-click an empty space within the directory window, select Properties from the context menu, and locate the number of items displayed next to the Contents label. Now, you can easily view the total number of files along with the total size of the directory.

      using a graphical interface to view files

      4. Execute watch and ls Commands

      The watch command in Linux is a valuable tool for monitoring file counts in real-time, as it helps to track changes or updates within a directory more efficiently. Constantly refreshing the output enables you to identify new files, deletions, or modifications as they happen. To utilize this command, execute the following in the Linux command prompt:

      watch -n 1 ls -l

      In the above command line, watch executes the ls -l command every 1 second and displays the output on the screen, allowing you to see any changes that occur in the directory as they happen.

      to identify changes in a directory

      To exit the watch interface in Linux, you can use the keyboard shortcut Ctrl + C. This will stop the watch command and return you to the command prompt.

      File Counting Techniques for Different Filesystems

      In Linux, counting files can vary slightly depending on the filesystem in use. Different filesystems like EXT4, XFS, and NTFS have unique features and performance characteristics. Here, I will explore specific commands and considerations for counting files in these filesystems, ensuring you get accurate results regardless of the environment.

      1. EXT4 Filesystem

      The EXT4 filesystem is a common type used in many Linux distributions. When you count files in an EXT4 filesystem, you can use basic commands like ls and find. These commands work well and give accurate counts. For example:

      • ls -l | wc -l lists all files in a directory and counts them.
      • find . -type f | wc -l finds and counts all files, including those in subdirectories.

      2. XFS Filesystem

      The XFS filesystem is another popular choice, especially for servers. Counting files in XFS works similarly to EXT4, but you might notice different performance characteristics because XFS handles large files and directories efficiently. Use the same commands:

      • ls -l | wc -l for listing and counting files in the current directory.
      • find . -type f | wc -l for counting all files in the current directory and its subdirectories.

      3. NTFS and Other Filesystems

      NTFS is a filesystem used by Windows, but you can access it from Linux using special tools. To count files in an NTFS filesystem on Linux, first mount the NTFS drive. Once mounted, use the same Linux commands to count files. For example:

      • ls -l /mnt/ntfs_drive | wc -l counts files in the NTFS drive’s mounted directory.
      • find /mnt/ntfs_drive -type f | wc -l finds and counts all files in the mounted NTFS directory.

      To Sum Up

      In this article, I’ve shown you various methods to count files in Linux, from basic commands like ls and find to advanced techniques using du and awk. I have also explored graphical methods for those who prefer a visual approach.

      If you want to expand your Linux knowledge further, check out these suggestions:

      Frequently Asked Questions

      What should I do if the file counting command in Linux returns an error?

      If you encounter an error while using a file counting command, double-check the syntax and make sure you are using the correct command for your specific task. If you continue to encounter errors, check the command’s documentation or seek assistance from Linux forums or communities.

      How can I count hidden files in Linux?

      To count hidden files in Linux, you can use the command below:
      find /path/to/directory -maxdepth 1 -type f -name ".*" | wc -l
      This command searches for files in the specified directory (/path/to/directory) up to a maximum depth of 1 (only in the specified directory, not in any subdirectories), with a type of f (only files, not directories), and a name that starts with a dot (hidden files). The output is then piped to the wc -l command to count the number of lines in the output, giving you the total number of hidden files in the specified directory.

      Can I count files across multiple directories at once?

      Yes, you can count files in Linux across multiple directories at once using the find command. For example, to count all .txt files in the /home/user/Documents and /home/user/Pictures directories, you can use the following command:
      find /home/user/Documents /home/user/Pictures -type f -name "*.txt" | wc -l

      How do I count the number of lines in a file in Linux?

      The wc (word count) command in Linux is used to count the number of lines, words, and characters in a file. To count only the number of lines, you can use the wc command with the -l flag, followed by the name of the file you want to count the lines in.
      wc -l filename.txt

      What is the difference between file count and disk usage?

      In Linux, file count and disk usage are two separate concepts that are both important to understand when managing files. File count refers to the number of files in a particular directory, while disk usage refers to the amount of disk space those files are taking up. Although the two are related, they measure different aspects of file management. Knowing both the file count and disk usage can help users better understand the content of a directory, monitor disk space usage, and make informed decisions about how to manage files.

      Ojash

      Author

      Ojash is a skilled Linux expert and tech writer with over a decade of experience. He has extensive knowledge of Linux's file system, command-line interface, and software installations. Ojash is also an expert in shell scripting and automation, with experience in Bash, Python, and Perl. He has published numerous articles on Linux in various online publications, making him a valuable resource for both seasoned Linux users and beginners. Ojash is also an active member of the Linux community and participates in Linux forums.

      Akshat

      Reviewer

      Akshat is a software engineer, product designer and the co-founder of Scrutify. He's an experienced Linux professional and the senior editor of this blog. He is also an open-source contributor to many projects on Github and has written several technical guides on Linux. Apart from that, he’s also actively sharing his ideas and tutorials on Medium and Attirer. As the editor of this blog, Akshat brings his wealth of knowledge and experience to provide readers with valuable insights and advice on a wide range of Linux-related topics.

      Share this article
      Shareable URL
      Prev Post

      How to Clear Bash History in Linux [3 Simple Ways]

      Next Post

      How to Unzip GZ Files in Linux [5 Proven Methods]

      Leave a Reply

      Your email address will not be published. Required fields are marked *

      Read next