2015-09-07 33 views
0

我正在使用find和sed命令替換文件中的字符。看到下面的代碼1將嵌套查找和sed命令放在其他位置

find . -type f -exec sed -i '/Subject/{:a;s/(Subject.*)Subject/\1SecondSubject/;tb;N;ba;:b}' {} + 

鑑於我有多個文件,我需要更換。在特定情況下,我試圖替換的主題不可用。 有沒有一種方法可以首先檢查文件是否包含屬性'主題',如果不是我需要執行另一個命令。即

檢查,如果該文件包含字符「主題」

如果爲true,則執行上述

代碼1如果沒有主題的情況下執行以下

find . -name "*.html" -exec rename 's/.html$/.xml/' {} ; 

任何想法碼2 ?在此先感謝

+0

在這種情況下使用'grep -r -l代替查找 – NeronLeVelu

回答

2

這樣的事情應該工作。

find . -type f \(\ 
-exec grep -q "Subject" {} \; \ 
-exec sed -i '/Subject/{:a;s/(Subject.*)Subject/\1SecondSubject/;tb;N;ba;:b}' {} \; \ 
-o \ 
-exec rename 's/.html$/.xml/' {} \; \) 

-exec需要它執行命令的退出代碼,所以-exec grep -q "Subject" {} \;如果grep的是真的只會是真實的。並且由於短路-o(或)的優先級低於其他運營商之間暗示的-a(和),所以它應該相反只有在grep爲假時纔會執行。

+0

它現在工作..謝謝 –

0

你可以在這樣的過程中替換使用find

while IFS= read -d'' -r file; do 
    echo "processing $file ..." 

    if grep -q "/Subject/" "$file"; then 
     sed -i '{:a;s/(Subject.*)Subject/\1SecondSubject/;tb;N;ba;:b}' "$file" 
    else if [[ $file == *.html ]]; then 
     rename 's/.html$/.xml/' "$file" 
    fi 
done < <(find . -type f -print0) 
+1

嗨Anub ..我會試一試並回復你。再次感謝 –