【问题标题】:Nesting Find and sed command in if else在 if else 中嵌套 Find 和 sed 命令
【发布时间】:2015-12-02 18:10:02
【问题描述】:

我正在使用 find 和 sed 命令替换文件中的字符。见下面的代码1

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

鉴于我需要替换多个文件。在特定情况下,我尝试替换的主题不可用。 有没有办法我可以先检查文件是否包含属性“主题”,如果没有,我需要执行另一个命令。即

检查文件是否包含字符“主题”

如果为真则执行上面的code1

如果没有Subject的实例,执行下面的代码2

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

有什么想法吗?提前致谢

【问题讨论】:

  • 在这种情况下使用 grep -r -l 而不是 find

标签: regex bash sed find


【解决方案1】:

这样的事情应该可以工作。

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 为假时才被执行。

【讨论】:

    【解决方案2】:

    您可以在这样的进程替换中使用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)
    

    【讨论】:

    • 嗨 Anub.. 我会试一试并回复你。再次感谢
    猜你喜欢
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    • 1970-01-01
    • 2017-04-14
    • 1970-01-01
    • 1970-01-01
    • 2013-11-13
    • 1970-01-01
    相关资源
    最近更新 更多