Posts tagged with “sed”

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 ensures sed works in binary mode, preserving the \r\n line endings.
  • The s/old_text/new_text/ part performs the actual substitution.

Using sed to insert a line after several lines after the match line

最近一直在写 .net core,它有诸多优点我且不提,我实在头痛于手写注入服务时的模式化代码,因此动了心思要写个小脚本帮我自动化一些事情。我的想法是告诉我要加入的 ServiceName, 指定一个 Controller然后脚本自动在这个 Controller 里声明一个 private readonly 属性,自动修改类的construction 函数,自动注入这个服务,并在construction 函数体写上 _serviceName = serviceName;

在第一步,注入 private readonly 属性那里,我就绊了个跟头。用 sed 匹配到某行,在它之前,或者之后插入数据是简单的。但我匹配到 public class xxxController 这行之后是单独一行 {,而我要加的变量要放到 {这行之后。网上一通搜索,试图找到定位到某行之后N行的命令,然而并没有这样的命令。然而功夫不负有心人,我最后还是找到了一个解决方案,那就是

sed '/pattern/!b;n;n;i\something'

具体解释见 Reference