Change the content of files but not change the date

I have 100 files in a directory , all the files have a word "error" and they are created in different date . Now I would like to change the word from "error" to "warning" , and keep the date of the files ( that means do not change the file creation date after change the word ) , can advise what can I do ?

thanks.

One option is to use touch to create a temporary file with the same timestamp as the original file, then use that to re-touch the original file once you have made your change.

$ touch -r file1 file1.tmp
$ ll file1*
-rw-r--r--  1 scott  staff   35 27 Nov 07:45 file1
-rw-r--r--  1 scott  staff    0 27 Nov 07:45 file1.tmp
$ vi file1
$ ll file1*
-rw-r--r--  1 scott  staff   36 17 Dec 18:50 file1
-rw-r--r--  1 scott  staff    0 27 Nov 07:45 file1.tmp
$ touch -r file1.tmp file1
$ ll file1*
-rw-r--r--  1 scott  staff   36 27 Nov 07:45 file1
-rw-r--r--  1 scott  staff    0 27 Nov 07:45 file1.tmp

thanks reply ,

can I do it in a batch , rather than do it for each file ?

Thanks .

for file in *.txt  # replace the extension as per your requirement.
do
        if [ $( grep -c error $file ) -ne 0 ]
        then
                TMPFILE=$( mktemp )
                touch -r $file $TMPFILE
                sed 's/error/warning/g' $file > tmp; mv tmp $file
                touch -r $TMPFILE $file
                rm -f $TMPFILE
        fi
done

thx reply ,

it works , but if I want to change the word is a string ( eg. please check the error ) rather than a single word , therefore what I want to do is change "please check the error" to "please check the the warning" , what can I do ?

thanks

Try this:

FROM="please check the error"
TO="please check the the warning"
 
for file in *.txt  # replace the extension as per your requirement.
do
        if grep -q "$FROM" "$file"
        then
                sed "s/$FROM/$TO/g" "$file" > tmp
                touch -r "$file" tmp
                mv tmp "$file"
        fi
done

when run the script , it pops the error

line 8: tmp: Is a directory

OK, best to use a different temp filename (leftover from bipinajith's code).

FROM="please check the error"
TO="please check the the warning"
 
for file in *.txt  # replace the extension as per your requirement.
do
        if grep -q "$FROM" "$file"
        then
                sed "s/$FROM/$TO/g" "$file" > tmp.$$
                touch -r "$file" tmp.$$
                mv tmp.$$ "$file"
        fi
done