I found (and adapted a bit) a command to edit a list of files using regex (and perl). I put it into a script file called cred, so I can do cred . england England to replace all occurrences of england with England in all files in the current directory.
find $1 -type f -exec perl -e 's/'$2'/'$3'/g' -p -i {} \;
It is wicked powerful, and already useful – but dangerous, and flawed. I would like it to…
- preview changes (or at least files operated on) first, asking confirmation
- work with longer strings than a single word. I tried
cred . england 'the United Kingdom'but it fails
I would also be interested in other (short and memorable, universally installed/installable on osx and ubuntu) commands to achieve the same thing.
EDIT:
This is what I have so far – open to improvements…
# highlight the spots that will be modified (not specifying the file)
find $1 -type f -exec grep -E "$2" --color {} \;
# get confirmation
read -p "Are you sure? " -n 1 -r
if [[ $REPLY =~ ^[Yy]$ ]]
then
# make changes, and highlight the spots that were changed
find $1 -type f -exec perl -e "s/$2/$3/g" -p -i {} \;
echo ""
find $1 -type f -exec grep -E "$3" --color {} \;
else
echo ""
echo "Aborted!!"
fi
To work on strings with spaces, write your command like:
If you use double quotes, variables will be expanded inside the quotes.
To do something like previewing changes and asking for confirmation you will need a much more complex script. One very easy thing to do would be to just run
find $1 -type ffirst to get a listing of all the files, and then use thereadcommand to get some input and decide if you should continue.