2017-02-01 90 views
0
for file in "$1"/* 

do 

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

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

    then 
blah 

blah 

上面的代碼遍歷目錄中的所有.c文件,並執行一些操作。我還想包括.cpp,.h,.cc文件。我在相同條件下檢查多個文件擴展名?如何從shell腳本搜索多個文件擴展名

感謝

回答

1

可以使用布爾運算符組合條件:

if [[ "$file" == *.c ]] || [[ "$file" == *.cpp ]] || [[ "$file" == *.h ]] || [[ "$file" == *.cc ]]; then 
    #... 
fi 

另一種方法是使用正則表達式:

if [[ "$file" =~ \.(c|cpp|h|cc)$ ]]; then 
    #... 
fi 
+0

我感興趣的第二個,但是從我的腳本運行時,我收到語法錯誤。 –

+0

./test_sed.sh:第20行:條件表達式中的語法錯誤 ./test_sed.sh:第20行:接近'\。'的'語法錯誤'(' ./test_sed.sh:第20行:'if [[「$ file 「=〜\。(c | cpp | h | cc)$]]' –

+0

@RakeshTalari如果我相信你的評論你有一個應該移除的'='和'〜'之間的空格('=〜'是正則表達式匹配運算符) – Aaron

3

爲什麼不遍歷選定的文件擴展名?

#!/bin/bash 

for file in ${1}/*.[ch] ${1}/*.cc ${1}/*.cpp; do 
    if [ -f $file ]; then 
     # action for the file 
     echo $file 
    fi 
done 
+0

從這個問題還不清楚在循環內是否忽略了其他文件,但是如果它們是讓shell的內部模式匹配器過濾掉其他文件,而不是在循環中顯式檢查它們 – chepner

+1

注意檢查'for'的結果確實是文件是很重要的,因爲除非'nullglob' shell選項具有已被設定,輕拍不與任何文件對應的tern將作爲字符串迭代。另外,序列可以縮寫爲'for file in $ 1/*。{c,h,cc,cpp};做...' – Aaron

2

使用擴展圖案,

# 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 = *[email protected](c|cc|cpp|h) ]]; then 
     ... 
    fi 
done 

延長圖案也可以是生成文件列表;在這種情況下,你肯定需要shopt命令:

shopt -s extglob nullglob 
for file in "$1"/*[email protected](c|cc|cpp|h); do 
    ... 
done 
+0

chepner,++。你還記得確切的發佈嗎? (太累了無法檢查源代碼):/ – heemayl

+1

看起來像是在4.1中添加的(請參閱https://tiswww.case.edu/php/chet/bash/CHANGES,第3項) – chepner