• Skip to primary navigation
  • Skip to main content
Sal Ferrarello
  • About Sal Ferrarello
  • Speaking
  • Connect
    Mastodon GitHub Twitter (inactive)
You are here: Home / Dev Tips / Remove newline at end of text file

Remove newline at end of text file

Last updated on February 10, 2022 by Sal Ferrarello

Sometimes when I’m working with files in Git, I find myself with a change in a file that says something like

-}
\ No newline at end of file
+}

Git diff with message 'No newline at end of file'.

This happens because the file had no newline at the end of the file but when I modify the file in my text editor the newline is added on save.

Why You Should Have a Newline at the End of the File

Officially, the Posix standard defines a line as

A sequence of zero or more non- <newline> characters plus a terminating <newline> character.

How to Remove the Newline at the End of the File

Even though the newline should appear at the end of the file, sometimes I’ll opt to remove it to minimize the “noise” in a commit. I’ve found the easiest way to do this is with

perl -pi -e 'chomp if eof' <myfile>

e.g.

perl -pi -e 'chomp if eof' composer.json

Alias

You can create an alias called chompeof by adding the following to your shell startup file (e.g. ~/.zshrc).

alias chompeof="perl -pi -e 'chomp if eof'"

See my Pull Request Add alias to remove newline at end of file to add this to my Zsh configuration.

Now I can use

chompeof composer.json
Sal Ferrarello
Sal Ferrarello (@salcode)
Sal is a PHP developer with a focus on the WordPress platform. He is a conference speaker with a background including Piano Player, Radio DJ, Magician/Juggler, Beach Photographer, and High School Math Teacher. Sal can be found professionally at WebDevStudios, where he works as a senior backend engineer.

Share this post:

Share on TwitterShare on FacebookShare on LinkedInShare on EmailShare on Reddit
Warning! This is a draft, not a finalized post. See full draft disclosure.

Filed Under: Computing, Dev Tips, Draft, Solution Tagged With: command line, Git

Reader Interactions

Comments

  1. Anil V says

    December 28, 2022 at 11:17 am

    i applied the same but not working
    in git diff it’s again keep showing .

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Copyright © 2023 · Bootstrap4 Genesis on Genesis Framework · WordPress · Log in