How to check if sed has changed a file

后端 未结 9 1296
难免孤独
难免孤独 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:13

    perl -sple '$replaced++ if s/$from/$to/g;
                    END{if($replaced != 0){ print "[Info]: $replaced replacement done in $ARGV(from/to)($from/$to)"}
                    else {print "[Warning]: 0 replacement done in $ARGV(from/to)($from/$to)"}}' -- -from="FROM_STRING" -to="$DESIRED_STRING" 
    

    Example: The command will produce the following output, stating the number of changes made/file.

    perl -sple '$replaced++ if s/$from/$to/g;
    END{if($replaced != 0){ print "[Info]: $replaced replacement done in $ARGV(from/to)($from/$to)"}
    else {print "[Warning]: 0 replacement done in $ARGV(from/to)($from/$to)"}}' -- -from="timeout" -to="TIMEOUT" *
    [Info]: 5 replacement done in main.yml(from/to)(timeout/TIMEOUT)
    [Info]: 1 replacement done in task/main.yml(from/to)(timeout/TIMEOUT)
    [Info]: 4 replacement done in defaults/main.yml(from/to)(timeout/TIMEOUT)
    [Warning]: 0 replacement done in vars/main.yml(from/to)(timeout/TIMEOUT) 
    

    Note: I have removed -i from the above command , so it will not update the files for the people who are just trying out the command. If you want to enable in-place replacements in the file add -i after perl in above command.

提交回复
热议问题