Removing carriage returns (^M) from certain lines without modifying every line

10,519

Solution 1

15 lines?

In notepad++, choose replace. Chose extended. Search for \r (which is ^M) and replace with nothing (unless you want a newline, then replace with \n). Since you do not want all ^M's replaced, do not press replace all, choose the ones you want to replace.

If you use regular windows notepad, the ^M's will show up as boxes. You can remove the boxes. Ugly, but it works.

Solution 2

Use dos2unix <file> if on command-line. It will fix line endings needed or do nothing if nothing is needed. Do a find . -name "*.cpp" -exec dos2unix {} + to do multiple files. Then compare with git diff before commit.

It is best to avoid ending up with mixed line endings in files. It can make merging and following history awkward.

Some editors will not change style but I think if even one ^M gets in file some editors will assume dos style and change all line endings when they write file.

It is usually possible to find settings for editors which will make the editor stick with the style you want. Line ending and tab settings also are usually set depending on style.

Solution 3

Git can do it automagically with git config --global core.autocrlf true. But it does it at checkout time or commit time. So git will not show up changes staged but should quietly take care of converting IF your editor introduces some new unwanted line endings.

I think use dos2unix if the unwanted line endings are already in repository.

For details, see the answer here: https://stackoverflow.com/questions/10418975/how-to-change-line-ending-settings and read http://git-scm.com/book/en/Customizing-Git-Git-Configuration#Formatting-and-Whitespace

Share:
10,519

Related videos on Youtube

Fasih Awan
Author by

Fasih Awan

Updated on September 18, 2022

Comments

  • Fasih Awan
    Fasih Awan over 1 year

    I have some fairly long C++ files, and git diff --check is reporting that there are a few carriage returns ^M on about 15 different lines. This is on a Windows 7 machine. After searching through several solutions, i.e. Visual Studio's Advanced Save Options, or Notepad++'s EOL Conversions, they all seem to be modifying every line, not only the ones Git is complaining about. This results in a git diff of every line being replaced.

    Could this be because all previous changes to these files also had carriage returns ^M and previous commits to it ignored any carriage return warnings?

    Running git config core.autocrlf returns true, but staging a file does nothing when I run git diff --cached --check for that file after staging it.

    Is there any way to remove them? Manually going to the line and trying to change doesn't seem to be helping.