Using Sed For Search and Replace

Posted in: Technical Track

I recently had a requirement to change the email for all shell scripts from personal ([email protected]) to a DBA list ([email protected]).

Typically, directories for shell scripts are scheduled using crontab. If shell scripts aren’t scheduled with crontab, then we’d need to find all the locations for shell scripts – this is beyond the scope of this post.

First, I checked crontab to find the shell scripts located in the directory /home/vagrant/scripts.

[[email protected] ~]$ crontab -l
5 4 * * * /home/vagrant/scripts/test.sh something > /tmp/test.out 2>&1
[[email protected] ~]$

[[email protected] ~]$ crontab -l|grep -v '#'|grep sh|awk '{print $6}'|sort -u
/home/vagrant/scripts/test.sh
[[email protected] ~]$

Next, I reviewed the shell scripts from the directory.

### Note: dt.sh is not schedule from crontab and resides in the same directory.

[[email protected] scripts]$ ls -l
total 12
-rwxrwxr-x. 1 vagrant vagrant  25 Feb  4 21:15 dt.sh
-rwxrwxr-x. 1 vagrant vagrant  20 Feb  4 21:14 test.sh
[[email protected] scripts]$

I created edit_email.sh to search and replace email from all shell scripts (.sh) using sed (stream editor).

Because the AIX version I tested doesn’t support in-place search and replace using sed, I had to create a temporary file.

The implementation below will work for most operating systems:

[[email protected] scripts]$ cat ./edit_email.sh
for infile in $(grep '[email protected]' *.sh|grep sh|awk -F':' '{print $1}'|sort -u|grep -v `basename $0`)
do
echo $infile
sed 's/\[email protected]\b/[email protected]/g' $infile > tmp.$$
mv tmp.$$ $infile
chmod 755 $infile
grep 'gmail.com' $infile
done
[[email protected] scripts]$

Finally, I ran edit_email.sh.

[[email protected] scripts]$ cat dt.sh
date
echo [email protected]
echo [email protected]
[[email protected] scripts]$

### Note: [email protected] and [email protected] did not get updated.

[[email protected] scripts]$ ./edit_email.sh
dt.sh
echo [email protected]
echo [email protected]
test.sh
export PAGER_EMAIL="[email protected]"
[[email protected] scripts]$

I hope you can see that using sed to search and replace is more more efficient and less prone to errors than editing each script manually.

If you have any thoughts or questions, please leave them in the comments.

email

Author

Want to talk with an expert? Schedule a call with our team to get the conversation started.

No comments

Leave a Reply

Your email address will not be published. Required fields are marked *