How to check if sed has changed a file

后端 未结 9 1184
难免孤独
难免孤独 2020-12-01 06:57

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

相关标签:
9条回答
  • 2020-12-01 07:32

    You can diff the original file with the sed output to see if it changed:

    sed -i.bak s:$pattern:$new_pattern: "$filename"
    if ! diff "$filename" "$filename.bak" &> /dev/null; then
      echo "changed"
    else
      echo "not changed"
    fi
    rm "$filename.bak"
    
    0 讨论(0)
  • 2020-12-01 07:34

    In macos I just do it as follows:

    changes=""
    changes+=$(sed -i '' "s/$to_replace/$replacement/g w /dev/stdout" "$f")
    if [ "$changes" != "" ]; then
      echo "CHANGED!"
    fi
    

    I checked, and this is faster than md5, cksum and sha comparisons

    0 讨论(0)
  • 2020-12-01 07:35

    A bit late to the party but for the benefit of others, I found the 'w' flag to be exactly what I was looking for.

    sed -i "s/$pattern/$new_pattern/w changelog.txt" "$filename"
    if [ -s changelog.txt ]; then
        # CHANGES MADE, DO SOME STUFF HERE
    else
        # NO CHANGES MADE, DO SOME OTHER STUFF HERE
    fi
    

    changelog.txt will contain each change (ie the changed text) on it's own line. If there were no changes, changelog.txt will be zero bytes.

    A really helpful sed resource (and where I found this info) is http://www.grymoire.com/Unix/Sed.html.

    0 讨论(0)
提交回复
热议问题