How to Use `sed` for Replacements on Windows Without Breaking Line Endings
When using sed
on Windows, you might run into unexpected behavior, especially with line endings. If you're editing files with Windows-style line endings (\r\n
), sed
can unintentionally modify them, causing issues with tools like git diff
. Here’s how you can use sed
effectively on Windows without breaking your line endings.
The Problem: Unexpected \r\n
to \n
Conversion
On Windows, text files usually use \r\n
(carriage return + line feed) as line endings. However, sed
, depending on its mode, may treat these as Unix-style \n
line endings, removing the \r
and leading to issues like:
- Files appearing changed when they shouldn’t.
- Tools like
git diff
showing extra changes due to the altered line endings.
Solution: Use sed -b
to Prevent Line Ending Conversion
To avoid this, you need to force sed
to operate in binary mode, which prevents automatic conversion of line endings.
Example:
sed -b 's/old_text/new_text/' filename.txt
In this example:
- The
-b
flag ensuressed
works in binary mode, preserving the\r\n
line endings. - The
s/old_text/new_text/
part performs the actual substitution.