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
1 |
mkdir tmp |
- Create a subdirectory
1 2 |
cd tmp mkdir data |
- Create two files
1 2 |
touch readme.txt touch run.sh |
- Add some lines of text to the readme file
1 2 |
echo "Hello 1" >> readme.txt echo "Hello 2" >> readme.txt |
- Make run.sh an executable file
1 |
chmod 755 run.sh |
- List all files and take a look at file types and permissions
1 |
ls -al |
You should see something like
1 2 3 |
drwxr-xr-x 2 username staff 68 Jul 9 11:07 data -rw-r--r-- 1 username staff 16 Jul 9 11:08 readme.txt -rwxr-xr-x 1 username staff 0 Jul 9 11:07 run.sh |
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
1 2 |
touch input.dat echo "My data" >> input.dat |
- Search by extension
1 |
find . -name *.txt |
This will print
1 |
./readme.txt |
- 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…
1 |
find . -type f -not -perm -111 |
Here is what we get
1 2 |
./input.dat ./readme.txt |
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
1 |
find . -type f -not -perm +111 -print -exec cat {} \; |
You get
1 2 3 4 5 |
./input.dat My data ./readme.txt Hello 1 Hello 2 |
- 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.
About Author
Mohammed Abualrob
Software Engineer @ Cisco