2012-03-23 85 views
0

對於顛簸的主題名稱感到抱歉(如果在查看問題後發現更合適的標題,請隨時編輯)。 代碼示例等於1000分的話,那麼在這裏我們去:有條件的命令在bash中的管道命令序列中執行

if [ "$REGEX" != "" ]; then 
     find $TEST_DIR -type f -regextype posix-extended -regex '^.*(status|stderr|stdout)-captured$' |         
     grep -E $REGEX | 
     awk '{print(""$1" "$1)}' | sed 's/-captured$/-expected/' | 
     while read -r line; do mv -f $line; done 
else 
     find $TEST_DIR -type f -regextype posix-extended -regex '^.*(status|stderr|stdout)-captured$' | 
     awk '{print(""$1" "$1)}' | sed 's/-captured$/-expected/' | 
     while read -r line; do mv -f $line; done 
fi 

什麼代碼所做的是並不那麼重要,我只是想找到更優雅的方式要麼使用「的grep -E $正則表達式」或不。我認爲條件化別名可以像我習慣使用shell一樣完成這項工作,但它們在腳本中不起作用。

我可以放入一個條件,但我擔心來自多個評估的性能影響。

任何方式來使代碼「更優雅」?

+0

你能描述一下你想要的輸入/輸出好一點嗎? – 2012-03-23 20:30:25

+0

@CarlNorum不要認爲這是必要的,但我應該:首先找到匹配名稱'{status,stderr,stdout)-captured'的文件的打印路徑,然後這些進一步被'grep -E $ REGEX'過濾。 awk,sed和read,組裝這個例子: './dir/status-captured'到執行的'mv ./dir/status-captured。/ dir/status-expected'中。 – AoeAoe 2012-03-23 20:36:11

回答

1

一個簡單的方法是使用^(始終一致:它的意思是「開始的行」,其中每行都有),如果$REGEX未設置或空白:

find $TEST_DIR -type f -regextype posix-extended -regex '^.*(status|stderr|stdout)-captured$' | 
grep -E ${REGEX:-^} | 
awk '{print(""$1" "$1)}' | sed 's/-captured$/-expected/' | 
while read -r line; do mv -f $line; done 

對於這個問題,你可以將其合併到原來的find

find $TEST_DIR -type f -regextype posix-extended \ 
    -regex '^.*(status|stderr|stdout)-captured$' \ 
    -regex ".*${REGEX}.*" | 
awk '{print(""$1" "$1)}' | sed 's/-captured$/-expected/' | 
while read -r line; do mv -f $line; done 

,並對於這個問題,您可以合併所有的腳本的其餘部分進入find還有:

find $TEST_DIR -type f -regextype posix-extended \ 
    -regex '^.*(status|stderr|stdout)-captured$' \ 
    -regex ".*${REGEX}.*" \ 
    -exec bash -c 'file="{}" ; mv -f "$file" "${file%-captured}-expected"' \; 
+0

有趣的是,第一個變體在我的測試樹中表現最好。 謝謝你真正有趣的答案。 – AoeAoe 2012-03-23 21:02:31

+0

@AoeAoe:不客氣! – ruakh 2012-03-23 21:06:27

1

一個很簡單的解決辦法是:

test -n "$REGEX" && cmd="grep -E $REGEX" 
find ... | ${cmd-cat} | awk ... 

如果CMD被定義,它在管中使用。否則,使用cat,執行no-op。 你也可以這樣做:

find ... | 
if test -n "$REGEX"; then 
    grep -E $REGEX 
else 
    cat 
fi | 
awk ... 

完全一樣的效果。

0

這是一個稍微難看,但一般的解決方案。

find $TEST_DIR -type f -regextype posix-extended -regex '^.*(status|stderr|stdout)-captured$' \ 
| if [ "$REGEX" != "" ]; then 
     grep -E $REGEX; \ 
    else \ 
     cat; \ 
    fi \ 
| awk '{print(""$1" "$1)}' \ 
| sed 's/-captured$/-expected/' \ 
| while read -r line; do mv -f $line; done