Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preserve timestamp in sed command

Tags:

linux

sed

rhel

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

like image 433
griboedov Avatar asked Nov 03 '16 03:11

griboedov


People also ask

How do I edit a file without changing the timestamp in Linux?

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.

What is P option in sed?

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.

What is E option in sed?

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.

How do you use sed multiple times?

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.


1 Answers

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:

  • cp -p

    -p same as --preserve=mode,ownership,timestamps

  • touch -r

    -r, --reference=FILE use this file's times instead of current time

  • touch -d

    -d, --date=STRING parse STRING and use it instead of current time


Reference:

  • Preserve modified time stamp after edit
  • Why does my shell script choke on whitespace or other special characters?
like image 140
Sundeep Avatar answered Oct 10 '22 09:10

Sundeep