1

我正在重新格式化文件,我想执行以下步骤:

  1. 用临时字符序列($CRLF$或其他东西)替换双 CRLF
  2. 删除整个文件中的所有 CRLF
  3. 返回并更换双CRLF。

所以像这样输入:

This is a paragraph
of text that has
been manually fitted
into a certain colum
width.

This is another
paragraph of text
that is the same.

会变成

This is a paragraph of text that has been manually fitted into a certain colum width.

This is another paragraph of text that is the same.

似乎这应该可以通过一些简单的sed程序来管道输入,但我不知道如何引用CRLFin sed(使用 in sed 's/<CRLF><CRLF>/$CRLF$/')。或者也许有更好的方法来做到这一点?

4

5 回答 5

1

您可以使用 sed 以 {CRLF} 结尾装饰所有行:

sed 's/$/<CRLF>/'

然后用 tr 删除所有 \r\n

| tr -d "\r\n"

然后用 \n 替换双 CRLF

| sed 's/<CRLF><CRLF>/\n/g'

并删除剩余的 CRLF。

有一个单线 sed 可以在一个周期内完成所有这些操作,但我现在似乎找不到它。

于 2012-07-09T11:08:01.710 回答
0

试试下面的:

cat file.txt | sed 's/$/ /;s/^ *$/CRLF/' | tr -d '\r\n' | sed 's/CRLF/\r\n'/

这不是您给出的方法;它的作用如下:

  1. 在每一行的末尾添加一个空格。
  2. 将任何仅包含空格(即空白行)的行替换为“CRLF”。
  3. 删除任何换行符(CR 和 LF)。
  4. 用 Windows 样式的换行符替换任何出现的字符串“CRLF”。

这对我来说适用于 Cygwin bash。

于 2012-07-09T11:17:53.930 回答
0

重新定义问题

看起来您真正想要做的是重新排列您的段落和单行间距。有多种方法可以做到这一点。

非 Sed 解决方案

如果你不介意在 coreutils 之外使用一些包,你可以使用一些额外的 shell 实用程序来使这变得简单:

dos2unix /tmp/foo
fmt -w0 /tmp/foo | cat --squeeze-blank | sponge /tmp/foo
unix2dos /tmp/foo

Sponge 来自moreutils包,它允许你编写你正在阅读的同一个文件。dos2unix(或者tofrodos )包将允许来回转换你的行尾,以便更容易地与期望 Unix 风格的行尾的工具集成。

于 2012-07-09T11:31:54.273 回答
0

这可能对您有用(GNU sed):

sed ':a;$!{N;/\n$/{p;d};s/\r\?\n/ /;ba}' file
于 2012-07-09T15:51:16.753 回答
0

我错过了为什么这不容易?

添加 CRLF:

sed -es/\s+$/$'\r\n'/ < index.html > index_CRLF.html

删除 CRLF... 去 unix:

sed -es/\s+$/$'\n'/ < index_CRLF.html > index.html

于 2016-05-27T15:19:10.957 回答