如何使用 sed 替换行首的文本?

How to replace text in the beginning of the line using sed?

我正在尝试 运行 一个 sed 脚本,其中以下行不起作用。

来自 sedfile.sed 文件:

s|^NEWLINE|XYZ|g

我想不通,为什么?

我正在 windows 并且正在 运行 使用批处理文件对其进行处理。

命令发出为:preprocess_answers.bat temp.text

preprocess_answers.bat

的内容
:preserving newline characters
fart -C %1 \r\n NEWLINE
sed -i -E -f preprocess_answers.sed %1

preprocess_answers.sed

的内容
#usage: sed -i -E -f preprocess_answers.sed  filename.tex
s|(NEWLINE *[0-9]+\. *)|\n|g
s|Hint|\tHint|g
#s|^NEWLINE([^\r\n\t]+)|\begin{finalanswer}  \end{finalanswer}|g
s|^NEWLINE|XYZ|g
s|\t(Hint[^\r\n]+)|\t\begin{hint}  \end{hint}|g

temp.text

的内容
1. (b)
2. (c)
3. (c)
4. (a)
5. (b)
1. asdf Hint: asdfasdf
1. asdf Hint: asdfasdf
1. asdf Hint: asdfasdf
1. asdf Hint: asdfasdf
1. asdf Hint: asdfasdf

在 运行 执行命令后,文本文件如下所示:

1. (b)
NEWLINE2. (c)
NEWLINE3. (c)
NEWLINE4. (a)
NEWLINE5. (b)
NEWLINE1. asdf      \begin{hint} Hint: asdfasdf \end{hint}
NEWLINE1. asdf      \begin{hint} Hint: asdfasdf \end{hint}
NEWLINE1. asdf      \begin{hint} Hint: asdfasdf \end{hint}
NEWLINE1. asdf      \begin{hint} Hint: asdfasdf \end{hint}
NEWLINE1. asdf      \begin{hint} Hint: asdfasdf \end{hint}

编辑:

我试图让注释掉的行:s|^NEWLINE([^\r\n\t]+)|\begin{finalanswer} \end{finalanswer}|g 工作,但由于它失败了,在调试过程中,我发现 ^ 是罪魁祸首。

sed 是一个流编辑器,它将流的每一行加载到模式 space 中,然后执行 您的 .sed 文件中的所有命令, 然后加载下一行,等等

除非您删除了所有换行符并将其替换为 'NEWLINE'。因此,您将所有内容加载到模式 space 中并同时处理所有内容。 (您可以使用 sed -z$!N;${...your commands} 或分支。)

无论如何,^ 匹配模式 space 的开头,而不是每一行的开头。我建议使用 \b 来表示 'word boundary',因为它是零 space。即:\bNEWLINE

您还应该查看您的系统上是否存在 dos2unixunix2dos 来处理整个 DOS 换行问题。