Linux script search and replace text string on multiple files


Objective: I need search and replace a specific text string on multiple files at once.

Solution: Using SED in a bash FOR loop to search for the text you want to replace.

for a in `find . -name '*filename*'`; do sed 's/text1/text2/g' $a > $a.bk; mv -f $a.bk $a; done;

In your FOR loop
Step 1: Find the files you want to modify
Step 2: Use sed to search and replace the contents and redirect it into a new file
Step 3: move the new file back to the old file
Step 4: close your loop with done

Note: You can put as many commands as I want in a FOR loop by using the ‘;’ delimiter.

Also, as the ‘>’ – redirect cannot be used to overwrite the current open file the trick is to split the operation into two; write to new file and then move back to old file.

Related Posts with Thumbnails

About the Author

Alfred Tong
Author and owner of this blog. A Networking enthusiast, full time networking and systems Engineer. Generally curious about all things IT.Certifications: GIAC GSEC, CCNP-S, CCNP, CCSP, CCDP, CCNA, RHCE, JNCIA - FWV