Skip to content

cmd - find命令的exec用法

From man find

-exec command {} +

This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command. The command is executed in the starting directory. If find encounters an error, this can sometimes cause an immediate exit, so some pending commands may not be run at all. This variant of -exec always returns true.

批量查找文件中的内容

find directory_to_search -type f -exec grep -inrH "content_to_find" {} \;
# -exec 表示执行后面的命令
# {} 表示前面find匹配到的文件名

批量修改git仓库下上游仓库地址

find directory_to_exec -maxdepth 3 -type f -name config -exec sed -i s#git@192.168.5.1:3022#git@gitlab.example.net:2022# {} \;
# 当有很多仓库时,可以批量执行该命令替换每个仓库下.git/config文件的地址信息

对查找的文件批量执行复杂的脚本任务

sudo find .  -type f -exec ./exec_script.sh {} {}-yancy \;

详细看下面的exec_script.sh

#!/bin/sh

# 查找被加密的文件,并对其进行一一解密,并还原其文件属性

# sudo find .  -type f -exec ./exec_script {} {}-yancy \; &
# {} 表示$1
# {}-yancy 表示$2

content=`file "$1" | awk -F: '{print $2}' | grep data`
# 匹配包含file命令中包含data的文件
if [ $? -ne 0 ]; then
    exit 0
fi

DecryptFile "$1" "$2" 
chmod --reference="$1" "$2"
chown --reference="$1" "$2"
mv "$2" "$1"

exit 0