简体   繁体   中英

Nesting Find and sed command in if else

I am using a find and sed command to replace characters in a file. see the code 1 below

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. ie

Check if the file contains character 'Subject'

If true then execute code1 above

If there is no instance of Subject execute code 2 below

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" {} \\; will only be true if the grep is 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.

You can use find in a process substitution like this:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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