about me about me
photography photography
software projects software projects
contact me contact me

Recently I tried to replace one line with multiple lines of text using Netbeans. As much as Netbeans IDE is growing on me (having recently switched from Eclipse), I couldn’t accomplish this multi-file, multi-line replace with it (yes I know about Edit > Replace in Projects… that didn’t work). I turned to bash for a solution …

The command that did the job (replacing one line with multiple in .php files):

find . -name "*.php" -type f | xargs grep -l "target string" \
| xargs grep -L "new line 2" | xargs sed -i 's/target string/line 1\nline 2\nline 3/g'

Lets pick this command apart to understand it better. First, find all .php files in the current path (recursive search):

find . -name "*.php" -type f

Filter this list of files to only those files containing out target string:

xargs grep -l "target string"

Optionally, to allow repeat runs of this command, filter out files containing the replacement text (grep’s -L switch negates files containing text matching the specified pattern):

xargs grep -L "new line 2"

Use sed to perform the substitution on the file, perform an in-place substitution (-i switch):

xargs sed -i 's/target string/line 1\nline 2\nline 3/g'

I recommend you test this command, to fine tune your sed pattern, before running it across many files. To do so, modify the find command and restrict it to a test file:

find . -name "MyTestFile.txt" -type f | xargs grep -l "foo" | xargs grep -L "bar" | xargs sed -i 's/foo/bar\nbar 2/g'

This command could be refactored into an easy to use multi-file replace script.


comments

No comments for this post.