I'm using following sed command to find and replace the string:
find dir -name '*.xml' -exec sed -i -e 's/text1/text2/g' {} \;
This changes the timestamp of all .xml files inside dir
However, how can I retain old timestamps?
Thanks
We can use one of the touch command's option -r (reference) to preserve file timestamps after editing or modifying it. The -r option is used to set the timestamps of one file to the timestamp values of another. As stated already, if we change the contents or metadata of this file, the timestamps will also change.
In sed, p prints the addressed line(s), while P prints only the first part (up to a newline character \n ) of the addressed line. If you have only one line in the buffer, p and P are the same thing, but logically p should be used.
The -e tells sed to execute the next command line argument as sed program. Since sed programs often contain regular expressions, they will often contain characters that your shell interprets, so you should get used to put all sed programs in single quotes so your shell won't interpret the sed program.
You can tell sed to carry out multiple operations by just repeating -e (or -f if your script is in a file). sed -i -e 's/a/b/g' -e 's/b/d/g' file makes both changes in the single file named file , in-place.
Using stat
and touch
find dir -name '*.xml' -exec bash -c 't=$(stat -c %y "$0"); sed -i -e "s/text1/text2/g" "$0"; touch -d "$t" "$0"' {} \;
Using cp
and touch
find dir -name '*.xml' -exec bash -c 'cp -p "$0" tmp; sed -i -e "s/text1/text2/g" "$0"; touch -r tmp "$0"' {} \;
From manuals:
-p same as --preserve=mode,ownership,timestamps
-r, --reference=FILE use this file's times instead of current time
-d, --date=STRING parse STRING and use it instead of current time
Reference:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With