There are many things we can do with some combination of find and other commands. We can use some commands on the files we find.

Let’s prepare some files and directories for demonstration:

1
2
3
4
5
6
7
8
9
echo "Some demo content" > find_usage01
echo "Some demo content" > find_usage02
echo "More demo content" > find_usage03
echo "Some demo content to be deleted" > find_to_be_deleted01
echo "Some demo content to be deleted" > find_to_be_deleted02
echo "More demo content to be deleted" > find_to_be_deleted03
mkdir find_dir01 find_dir02 find_dir03
ll | grep 'find*'
cat find_usage01 find_usage02 find_usage03
img

Create some demo files and print out the contents

Run Command on One File or More Files

We can apply a command on top of a single file or multiple files that match.

We can apply a command to each matching file individually with the execdir option combined with the {} symbol:

img

Run the cat command on each file individually

We can move the {} symbol to the end and ends with a + symbol to apply the command to all matching files at the same time:

img

Run the cat command on all files at the same time

Remove Matching Files

By adding the -delete option, we can delete the matching files:

1
2
find -name '*to_be_deleted*' -delete
ll | grep 'find*'
img

Outputs the files whose name begins with find after removing the matching files

Change Permissions of the Matching Files

We can specify the type of file to which the chmod command applies through the -type option of the find command.

Change Permissions of the Matching Regular Files

Let’s enable user group’s write permission on the matching files:

1
2
3
ll | grep 'find*'
find -type f -name 'find*' -execdir chmod g+w {} +
ll | grep 'find*'
img

Outputs all the files whose name begins with find before and after changing the group permission of the matching files

Change Permissions of the Matching Directories

Let’s enable user group’s write permission on the matching directories:

1
2
3
ll | grep 'find*'
find -type d -name 'find*' -execdir chmod g+w {} +
ll | grep 'find*'
img

Outputs all the files whose name begins with find before and after changing the group permission of the matching directories

References 3 Actions, 9 Common Tasks

Buy me a coffeeBuy me a coffee