How to check if sed has changed a file

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

    Don't use sed to tell if it has changed a file; instead, use grep to tell if it is going to change a file, then use sed to actually change the file. Notice the single line of sed usage at the very end of the Bash function below:

    # Usage: `gs_replace_str "regex_search_pattern" "replacement_string" "file_path"`
    gs_replace_str() {
        REGEX_SEARCH="$1"
        REPLACEMENT_STR="$2"
        FILENAME="$3"
    
        num_lines_matched=$(grep -c -E "$REGEX_SEARCH" "$FILENAME")
        # Count number of matches, NOT lines (`grep -c` counts lines), 
        # in case there are multiple matches per line; see: 
        # https://superuser.com/questions/339522/counting-total-number-of-matches-with-grep-instead-of-just-how-many-lines-match/339523#339523
        num_matches=$(grep -o -E "$REGEX_SEARCH" "$FILENAME" | wc -l)
    
        # If num_matches > 0
        if [ "$num_matches" -gt 0 ]; then
            echo -e "\n${num_matches} matches found on ${num_lines_matched} lines in file"\
                    "\"${FILENAME}\":"
            # Now show these exact matches with their corresponding line 'n'umbers in the file
            grep -n --color=always -E "$REGEX_SEARCH" "$FILENAME"
            # Now actually DO the string replacing on the files 'i'n place using the `sed` 
            # 's'tream 'ed'itor!
            sed -i "s|${REGEX_SEARCH}|${REPLACEMENT_STR}|g" "$FILENAME"
        fi
    }
    

    Place that in your ~/.bashrc file, for instance. Close and reopen your terminal and then use it.

    Usage:

    gs_replace_str "regex_search_pattern" "replacement_string" "file_path"
    

    Example: replace do with bo so that "doing" becomes "boing" (I know, we should be fixing spelling errors not creating them :) ):

    $ gs_replace_str "do" "bo" test_folder/test2.txt 
    
    9 matches found on 6 lines in file "test_folder/test2.txt":
    1:hey how are you doing today
    2:hey how are you doing today
    3:hey how are you doing today
    4:hey how are you doing today  hey how are you doing today  hey how are you doing today  hey how are you doing today
    5:hey how are you doing today
    6:hey how are you doing today?
    $SHLVL:3 
    

    Screenshot of the output:

    References:

    1. https://superuser.com/questions/339522/counting-total-number-of-matches-with-grep-instead-of-just-how-many-lines-match/339523#339523
    2. https://unix.stackexchange.com/questions/112023/how-can-i-replace-a-string-in-a-files/580328#580328

提交回复
热议问题