How to Run find -exec Command in Bash
This article will explain how to use the find
command’s -exec
parameter to locate any text in a file using the find
command.
Use the find
Command to Search Files in Bash
A find
command is a useful tool for searching and selecting files in bash. We use the find
command with some expressions and actions.
Example:
find ./folder -name *.txt
We use the find
command with a search location, such as ./folder
for the folder
directory and its sub-directories. And the -name *.txt
expression is to find every .txt
file in the location.
Use -exec
Option With the find
Command to Search Files in Bash
We can use the -exec
action to run commands on the files found by the find
command using the find
command.
Example:
find ./folder -name *.txt -exec file {} +
Output:
./folder/hello.txt: ASCII text, with no line terminators
The -exec
action runs the file
command, displaying the file type returned by the find
command.
Use find -exec
Command to Search for a Specific Text in Bash
We can use the find
command with the -exec
option to find the files that contain the text we want to search.
The main concept is to use the find
command to get each file in the working directory and execute the grep
command to find the text in each file.
Example:
# !/bin/bash
find . -exec grep linux {} \;
The following command will return the lines where the specified text
is found.
Output:
find . -exec grep linux {} \;
find . -exec grep linux {} +
title = "Unzip .gz file in linux"
description = "How to unzip a .gz file in linux"
To prevent the shell from interpreting the ;
delimiter, we use \
before it. Using this strategy, we only get the lines where text was detected.
We can get the lines as well as the filename where it was found by replacing the delimiter ;
with a +
.
# !/bin/bash
find . -exec grep linux {} +
Output:
./bash.sh:find . -exec grep linux {} \;
./bash.sh:find . -exec grep linux {} +
./unzip_gz_linux.txt:title = "Unzip .gz file in linux"
./unzip_gz_linux.txt:description = "How to unzip a .gz file in linux"
The way find
handles the expression results is determined by the delimiter. The -exec
command will repeat for each result independently if we use the semicolon ;
.
If we use the +
sign, all of the expressions’ results will be concatenated and provided to the -exec
command, only running once. We prefer to use the +
delimiter for performance reasons.