[英]Nesting Find and sed command in if else
我正在使用find和sed命令替換文件中的字符。 參見下面的代碼1
find . -type f -exec sed -i '/Subject/{:a;s/(Subject.*)Subject/\1SecondSubject/;tb;N;ba;:b}' {} +
鑒於我有多個文件,我需要替換。 在給定的情況下,我要替換的主題不可用。 有沒有一種方法可以首先檢查文件是否包含屬性“ Subject”(如果不是),則不需要執行其他命令。 即
檢查文件是否包含字符“主題”
如果為true,則執行上面的代碼1
如果沒有Subject的實例,請執行下面的代碼2
find . -name "*.html" -exec rename 's/.html$/.xml/' {} ;
有任何想法嗎? 提前致謝
這樣的事情應該起作用。
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為true時才為true。 而且由於其他運算符之間的短路-o
(或)的優先級比隱含的-a
(和)的優先級低,因此相反,只有在grep
為false時才應執行。
您可以在流程替代中使用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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.