How to find text only files on Linux

Introduction

On Unix based operating systems (Linux, MacOS, etc) a common task is to search for files. For example, we may need to search for text files only. In this post, we will demonstrate the command line syntax to filter out binary and executable files and only keep text files. Follow the steps below…

  • Create a temporary directory

  • Create a subdirectory

  • Create two files

  • Add some lines of text to the readme file

  • Make run.sh an executable file

  • List all files and take a look at file types and permissions

You should see something like

Note that the data directory has the (d) flag and the run.sh file has the executable flag (x).

  • Create a text file with dat extension

  • Search by extension

This will print

  • Find all text files

Note that the extension is not going to help us find all text files. Let us see how to do it…

Here is what we get

The command above means find in the current directory all files (do not list directories) that do not have the executable flag set. Note that the find command is very sophisticated, we can go fancy, here are some options…

  • Execute a command

We can execute a command against the files found by the find command. In the example below, we are going to find all non executable files, print the file name then print the content of the file

You get

  • Ignoring case

You can use -iname to ignore case

  • Filter by size

We can use the -size option to filter files by size. For example -size +1M will only include files with 1 or more megabytes in size. For more options, you can refer to the manual. That is it for today. Thanks for visiting.

Tags:

Add a Comment

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