简体   繁体   English

在其他情况下嵌套Find和sed命令

[英]Nesting Find and sed command in if else

I am using a find and sed command to replace characters in a file. 我正在使用find和sed命令替换文件中的字符。 see the code 1 below 参见下面的代码1

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

Given that I have multiple files I need to replace. 鉴于我有多个文件,我需要替换。 In a given situation, the Subject I am trying to replace is not available. 在给定的情况下,我要替换的主题不可用。 Is there a way I can first check if the file contains the attribute 'Subject' if not I need to execute another command. 有没有一种方法可以首先检查文件是否包含属性“ Subject”(如果不是),则不需要执行其他命令。 ie

Check if the file contains character 'Subject' 检查文件是否包含字符“主题”

If true then execute code1 above 如果为true,则执行上面的代码1

If there is no instance of Subject execute code 2 below 如果没有Subject的实例,请执行下面的代码2

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

Any Ideas? 有任何想法吗? Thanks in advance 提前致谢

Something like this should work. 这样的事情应该起作用。

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 takes the exit code of the command it executes, so -exec grep -q "Subject" {} \\; -exec获取执行命令的退出代码,因此-exec grep -q "Subject" {} \\; will only be true if the grep is true. 仅当grep为true时才为true。 And since the short circuit -o (or) has a lower precedence than the implied -a (and) between the other operators it should conversely only get executed if the grep is false. 而且由于其他运算符之间的短路-o (或)的优先级比隐含的-a (和)的优先级低,因此相反,只有在grep为false时才应执行。

You can use find in a process substitution like this: 您可以在流程替代中使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM