如何检查sed是否更改了文件 [英] How to check if sed has changed a file

查看:37
本文介绍了如何检查sed是否更改了文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种聪明的方法来确定传递给 sed 的文件是否已成功更改.

I am trying to find a clever way to figure out if the file passed to sed has been altered successfully or not.

基本上,我想知道文件是否被更改,而不必查看文件修改日期.

Basically, I want to know if the file has been changed or not without having to look at the file modification date.

我需要这个的原因是因为如果 sed 成功替换了一个模式,我需要做一些额外的事情.

The reason why I need this is because I need to do some extra stuff if sed has successfully replaced a pattern.

我目前拥有:

    grep -q $pattern $filename
    if [ $? -eq 0 ]
    then
        sed -i s:$pattern:$new_pattern: $filename
                # DO SOME OTHER STUFF HERE
    else
        # DO SOME OTHER STUFF HERE
    fi

上面的代码有点贵,我很想在这里使用一些技巧.

The above code is a bit expensive and I would love to be able to use some hacks here.

推荐答案

你可以使用 awk 代替:

awk '$0 ~ p { gsub(p, r);t=1} 1 END{ exit (!t) }' p="$pattern" r="$repl"

我忽略了 -i 功能:您可以根据需要使用 shell 进行重定向.

I'm ignoring the -i feature: you can use the shell do do redirections as necessary.

叹气.下面的许多评论要求提供有关 shell 的基本教程.您可以使用上面的命令如下:

Sigh. Many comments below asking for basic tutorial on the shell. You can use the above command as follows:

if awk '$0 ~ p { gsub(p, r); t=1} 1 END{ exit (!t) }' 
        p="$pattern" r="$repl" "$filename" > "${filename}.new"; then
    cat "${filename}.new" > "${filename}"
    # DO SOME OTHER STUFF HERE
else
    # DO SOME OTHER STUFF HERE
fi

我不清楚DO SOME OTHER STUFF HERE"在每种情况下是否相同.两个块中任何类似的代码都应该相应地重构.

It is not clear to me if "DO SOME OTHER STUFF HERE" is the same in each case. Any similar code in the two blocks should be refactored accordingly.

这篇关于如何检查sed是否更改了文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆