如何从shell脚本中搜索多个文件扩展名

Rak*_*ari 6 bash grep sed

for file in "$1"/*

 do

    if [ ! -d "${file}" ] ; then

   if [[ $file == *.c ]]

    then
blah

blah
Run Code Online (Sandbox Code Playgroud)

上面的代码遍历目录中的所有 .c 文件并执行一些操作。我也想包含 .cpp、.h、.cc 文件。如何在同一 if 条件下检查多个文件扩展名?

谢谢

Aar*_*ron 6

您可以使用布尔运算符组合条件:

if [[ "$file" == *.c ]] || [[ "$file" == *.cpp ]] || [[ "$file" == *.h ]] || [[ "$file" == *.cc ]]; then
    #...
fi
Run Code Online (Sandbox Code Playgroud)

另一种选择是使用正则表达式:

if [[ "$file" =~ \.(c|cpp|h|cc)$ ]]; then
    #...
fi
Run Code Online (Sandbox Code Playgroud)


che*_*ner 5

使用扩展模式,

# Only necessary prior to bash 4.1; since then,
# extglob is temporarily turn on for the pattern argument to !=
# and =/== inside [[ ... ]]
shopt -s extglob nullglob

for file in "$1"/*; do
    if [[ -f $file && $file = *.@(c|cc|cpp|h) ]]; then
        ...
    fi
done
Run Code Online (Sandbox Code Playgroud)

扩展模式还可以是生成文件列表;在这种情况下,你肯定需要shopt命令:

shopt -s extglob nullglob
for file in "$1"/*.@(c|cc|cpp|h); do
    ...
done
Run Code Online (Sandbox Code Playgroud)