Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent sed from adding newlines at the end of files

Tags:

git

bash

sed

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.)

like image 654
Torstein Avatar asked Jul 13 '16 14:07

Torstein


People also ask

Should files have newlines at the end?

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.

Why have new line at the end of file?

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.

How do you use sed to substitute a new line?

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.


1 Answers

Perl to the rescue:

perl -i -pe 's/Foo/Bar/g'

Perl doesn't add newlines.

like image 139
choroba Avatar answered Oct 07 '22 12:10

choroba