2017-02-15 52 views
1

我想從我的數組中取消設置名稱中有兩個'_'字符的文件夾。但我得到權限被拒絕的錯誤。你能幫我解決嗎?這裏是我的腳本,它的輸出:在shell腳本中使用echo結果如果在一個shell腳本中檢查

#!/bin/sh 

ALLVERSION=(/dir/test*) 
echo "first version:" 
for ((i=0; i<${#ALLVERSION[@]}; i++)); do 
    if [[ `${ALLVERSION[i]} | grep -o '_' | wc -l` -eq 2 ]]; then 
    unset ALLVERSION[i] 
    fi 
done 
echo "last version:" 
for f in "${ALLVERSION[@]}"; do 
    echo "$f" 
done 

結果:

first version: 
countcharacter.sh: line 6: /dir/test03_01.txt: Permission denied 
countcharacter.sh: line 6: /dir/test03_01_01.txt: Permission denied 
countcharacter.sh: line 6: /dir/test03_01_04.txt: Permission denied 
countcharacter.sh: line 6: /dir/test03_04.txt: Permission denied 
countcharacter.sh: line 6: /dir/test03_05_04.txt: Permission denied 
countcharacter.sh: line 6: /dir/test04_01_04.txt: Permission denied 
countcharacter.sh: line 6: /dir/test05_00.txt: Permission denied 
countcharacter.sh: line 6: /dir/test05_01.txt: Permission denied 
countcharacter.sh: line 6: /dir/test06_01.txt: Permission denied 
last version: 
/dir/test03_01.txt 
/dir/test03_01_01.txt 
/dir/test03_01_04.txt 
/dir/test03_04.txt 
/dir/test03_05_04.txt 
/dir/test04_01_04.txt 
/dir/test05_00.txt 
/dir/test05_01.txt 
/dir/test06_01.txt 
+0

如果[['回聲$ {ALLVERSION [I]} | grep -o'_'| wc -l' -eq 2]];那麼 – zzn

回答

1

您必須echo ${ALLVERSION[i]}它管道到grep前:

if [[ `echo ${ALLVERSION[i]} | grep -o '_' | wc -l` -eq 2 ]]; then 

沒有echo執行存儲在${ALLVERSION[i]文件和其輸出傳遞給grep

請注意,對於命令替換,您應該使用$(yourcommand)語法,建議在使用反引號`yourcommand`時使用該語法。

+0

它現在正在工作,非常感謝! –

1

除了這個有用的SLePort's answer,您可以單獨使用本地bash工具來實現您的要求,而不是分叉任何第三方工具。

echo "first version:" 
for ((i=0; i<${#ALLVERSION[@]}; i++)); do 

    # Strip every character that is not '_', so "${#count}" will be 2 for 
    # those lines containing two '_' 
    count="${ALLVERSION[i]//[!_]/}" 

    if (("${#count}" == 2)); then 
     unset ALLVERSION[i] 
    fi 
done 

echo "last version:" 
for f in "${ALLVERSION[@]}"; do 
    echo "$f" 
done 
+1

沒有命令替換,沒有管道,以及更多的可讀性...... – SLePort

+0

@SLePort:感謝您的反饋,如果您可以推薦'$()'語法而不是過時的,容易出錯的語法 – Inian

1

除非您正在處理文件的每一行,否則很少需要grep。對於單行輸入,請使用bash的正則表達式運算符。

if [[ ${ALLVERSION[i]} =~ /dir/test_[^_]*_[^_]* ]]; then 
    unset ALLVERSION[i] 
fi 

或使用擴展模式匹配:

# If you are using an older version of bash, you'll need 
# to set the extglob option first. 
# shopt -s extglob 
if [[ ${ALLVERSION[i]} == /dir/test_*(!(_))_*(!(_)) ]]; then 
    unset ALLVERSION[i] 
fi