Yesterday at work, I came across a need to search and replace text across multiple files. The sed command seemed to be the appropriate command. On my Macbook Pro computer, sed needs a few different inputs than its Linux counterparts. While I was able to find the fact that if you want sed to copy the changes to the original files, (you need to do something like this: sed -i "" "s/form/forms/g" The "" being very important. As I found at: http://dev.totodotnet.net/post/17360058466/using-sed-command-in-mac-os-x This alone, however doesn't do what I wanted. I needed to feed in text as sed is really a text stream reader. To feed in the proper text, I found that you can do this:
find . -name '*.txt' -print0 | xargs -0 sed -i "" "s/form/forms/g"
Placing the period allows the command to know to search through sub-directories. This was the key point that I needed as I didn't want to do this for just one file. Of course form and forms would be replaced with a regular expression that would search and replace text that you wanted to change.
Another thing that I learned is that if you want to use a regular expression variable in the aforementioned sed command, you need to use ( ) to enclose the saved portion, and then use a backslash one like this: \1 to use this save information from the select portion. Of course you can have more than one set of parenthesis, so you would need to use \2 and other numbers as seen fit.
No comments:
Post a Comment