Friday, June 20, 2008

Linux Search and Replace multiple files

I don't know how many times I've forgotten how to do this but here's the summary.

Objective: I have some text I want to modify in many files.

Solution: Using SED in a bash FOR loop

for a in `find . -name '*filename*'`; do sed 's/text1/textx2/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

The trick I forgot here is I 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.

No comments: