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/ something > /tmp/test.out 2>&1
[[email protected] ~]$

[[email protected] ~]$ crontab -l|grep -v '#'|grep sh|awk '{print $6}'|sort -u
[[email protected] ~]$

Next, I reviewed the shell scripts from the directory.

### Note: 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
-rwxrwxr-x. 1 vagrant vagrant  20 Feb  4 21:14
[[email protected] scripts]$

I created 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 ./
for infile in $(grep '[email protected]' *.sh|grep sh|awk -F':' '{print $1}'|sort -u|grep -v `basename $0`)
echo $infile
sed 's/\[email protected]\b/[email protected]/g' $infile > tmp.$$
mv tmp.$$ $infile
chmod 755 $infile
grep '' $infile
[[email protected] scripts]$

Finally, I ran

[[email protected] scripts]$ cat
echo [email protected]
echo [email protected]
[[email protected] scripts]$

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

[[email protected] scripts]$ ./
echo [email protected]
echo [email protected]
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.



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 *