I have a large project where I want to replace module names using the following command:
find app/ -type f -exec sed -i '' 's/Foo/Bar/g' {} +
This works great, but sed also adds newlines to the end of all the files (even if it can't find any Foo's to replace).
How can I prevent sed from adding these newlines?
I'm on OSX, using the BSD version of sed.
(For the record, I very much agree with sed here, but I dont want to pollute the git history of the project.)
So, it turns out that, according to POSIX, every text file (including Ruby and JavaScript source files) should end with a \n , or “newline” (not “a new line”) character. This acts as the eol , or the “end of line” character.
If content is added to the end of the file, then the line that was previously the last line will have been edited to include a newline character. This means that blame ing the file to find out when that line was last edited will show the text addition, not the commit before that you actually wanted to see.
Using `sed` to replace \n with a comma By default, every line ends with \n when creating a file. The `sed` command can easily split on \n and replace the newline with any character. Another delimiter can be used in place of \n, but only when GNU sed is used.
Perl to the rescue:
perl -i -pe 's/Foo/Bar/g'
Perl doesn't add newlines.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With