Skip to content

Instantly share code, notes, and snippets.

@bsavage
Last active August 19, 2019 19:35
Show Gist options
  • Select an option

  • Save bsavage/9d44d141d1c5dad0574ba0d80d12b549 to your computer and use it in GitHub Desktop.

Select an option

Save bsavage/9d44d141d1c5dad0574ba0d80d12b549 to your computer and use it in GitHub Desktop.
Linux Script to prompt for string replacement, replace in file and preserve original file modification time.

Prompt for and Replace string in file while preserving original modification data

This gist repo contains a linux bash script that:

  • prompts for file to convert
  • string to be replaced
  • string to replace with It converts the file and preserves the original file modfication datatime. This is very useful when moving files across servers and other cases where the files hasn't changed materially except for some arbitrary (often server-specific) string. Note that / can be part of string as well as any other character other than %
#set -x
echo "This will allow prompted string replacement in a file"
echo "while preserving the original file modification date"
echo "(most useful when moving files across servers)"
echo "Note that / can be used in the replacement strings, % cannot"
echo " "
read -p "File to convert: " oldfl
read -p "String to replace: " oldstr
read -p "String to replace with: " newstr
echo -e "\nFile before update(s) *******************************************"
ls -al $oldfl
cat $oldfl
touch -r $oldfl savetime
line_new='ver009'
sed -e "s%$oldstr%$newstr%g" $oldfl > tempfl
mv tempfl $oldfl
touch -r savetime $oldfl
rm savetime
echo -e "\nFile after update(s) :$oldfl ************************************"
ls -al $oldfl
cat $oldfl
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment