14

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

griboedov
  • 876
  • 3
  • 16
  • 33

3 Answers3

17

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:

Sundeep
  • 23,246
  • 2
  • 28
  • 103
2

Instead of copying the entire file, you can use

touch -r <file>  tmp 

so you save the timestamp in the tmp file but no content ...

user30424
  • 147
  • 1
  • 10
0

I have managed to insert the timestamp on each file and keeping the original one:

(
cd ~/.dotfiles/wiki
for file in *.md; do
    echo "Changing file: $file .."
    t=$(stat -c "%y" "$file") # original timestamp
    new_date=$(date -r "$file" +'%a, %d %b %Y - %H:%M:%S')
    sed -i "1,7s/\(Last Change: \).*/\1 $new_date/g" "$file"
    touch -d "$t" "$file"
done
)

In my case the files I needed to change where my markdown folders inside my wiki folder

SergioAraujo
  • 11,069
  • 3
  • 50
  • 40