How to replace all occurrences of a word with another word in all files in multiple directories and their sub-directories using bash?

I have a need to replace all email addresses of form admin@xxxx.com or admin@yyy.net or admin@zzzzz.org with root@localhost in all files under several folders and all their sub-folders. How can I do it with bash programming?

find dir1 dir2 dir3 dir4 -type f -exec sed -i 's/admin@.\{1,27\}\.\(com\|net\|org\)/root@localhost/g' {} \;

The -i option tells sed to do in-place replacement.  The regexp in sed is complex which I will explain in details.

The regular expression(pattern) in sed is put in //. The dot symbol in regexp has special meaning, i.e., denoting any character. So to match the dot character itself, you should escape it with \.

Interestingly, the characters {,} and (,),| which have special meanings  do not need to be escaped if you want their literal meanings. Instead, you need to escape them with \ to obtain their special meanings. If you do not escape them with \, they are just matched against {,}, (,),|.

More interestingly, the character [-] which have special meanings do not need to be escaped to use their special meanings. However, you need to escape them if you want their literal meanings. The -, if not escaped, has its literal meaning when not in [] context, but has its regexp meaning when in [] context. The -, if escaped, still has its regexp meaning when in [] and has literal meaning when not in [] context.

 

 

Did you like this?
Tip admin with Cryptocurrency

Donate Bitcoin to admin

Scan to Donate Bitcoin to admin
Scan the QR code or copy the address below into your wallet to send some bitcoin:

Donate Bitcoin Cash to admin

Scan to Donate Bitcoin Cash to admin
Scan the QR code or copy the address below into your wallet to send bitcoin:

Donate Ethereum to admin

Scan to Donate Ethereum to admin
Scan the QR code or copy the address below into your wallet to send some Ether:

Donate Litecoin to admin

Scan to Donate Litecoin to admin
Scan the QR code or copy the address below into your wallet to send some Litecoin:

Donate Monero to admin

Scan to Donate Monero to admin
Scan the QR code or copy the address below into your wallet to send some Monero:

Donate ZCash to admin

Scan to Donate ZCash to admin
Scan the QR code or copy the address below into your wallet to send some ZCash:

Leave a Reply