user1166981
user1166981

Reputation: 1746

Possible to grep and modify/touch the file modification date?

I am using the following to find all instances of a string in a number of files and delete the line where they are found.

find . -maxdepth 1 -xdev -type f -exec sed -i '/teststring/Id' {} \;

I don't want to change the date the file was modified because that impacts on the order that the files are shown in an unrelated application. So I was thinking I could grab the date before executing sed, then touch the file and replace the old modify date at the end of the command. I want to have it all in one command integrated with the above if possible.

Upvotes: 0

Views: 1174

Answers (2)

Gaurav Pal
Gaurav Pal

Reputation: 11

for file in $(find . -maxdepth 1 -xdev -type f )
do
   mod_time=$(stat --format=%y $file)
   perl -wpl -i -e 's!teststring!!' $file
   touch -d ''$mod_time'' $file

done

Upvotes: 1

dogbane
dogbane

Reputation: 274612

Try the following command:

find . -maxdepth 1 -xdev -type f -exec sed -i.bak '/teststring/Id' {} \; -exec touch -r {}.bak {} \; -exec rm {}.bak \;

The find command executes three steps for each file found:

  1. sed changes the file and creates a backup of the original file (with a .bak extension)
  2. touch sets the timestamp of the new file to be the same as the backup
  3. rm deletes the backup

Upvotes: 2

Related Questions