Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix “No newline at end of file” warning for lots of files?

I have a huge number of source files that are all lacking a newline at the end.

How do I automatically add a newline to the end of each of them?

Some may already have a newline, so it should only be added if necessary.

I'm probably not looking for code, per se, but just something I can run in Terminal to add the necessary newlines (or some kind of programming or development tool).

like image 207
Elliot Avatar asked Jul 16 '10 04:07

Elliot


People also ask

Why does git say no new line at end of file?

It just indicates that the end of the file doesn't have a newline.

Should all files end with a newline?

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.

How do I add a line to the end of a file?

Append Text Using >> Operator Alternatively, you can use the printf command (do not forget to use \n character to add the next line). You can also use the cat command to concatenate text from one or more files and append it to another file.


1 Answers

Converted Norman's answer to a split one-liner for convenience.

for i in * ; do  echo $i; \
 if diff /dev/null "$i" | tail -1 | \
  grep '^\\ No newline' > /dev/null; then echo >> "$i"; \
 fi; done

Replace * with whatever file pattern you want, eg *.c

And another to just tell you which files are broken:

for i in * ; do \
 if diff /dev/null "$i" | tail -1 | \
  grep '^\\ No newline' > /dev/null; then  echo $i; \
 fi; done
like image 179
Tim Abell Avatar answered Sep 18 '22 22:09

Tim Abell