对 bash 中的段落进行排序(awk 或 sed)?

Sorting paragraphs in bash (awk or sed)?

我尝试对各个段落进行排序(abc 顺序):

awk 'BEGIN { RS="" } { a[FNR]=[=13=] } END { PROCINFO["sorted_in"]="@val_str_asc" for (i in a) print a[i] ORS } ' myrecords.txt

但它不会排序。样本记录:

Ham  
this is good  
(mind the mail)

Cheese  
I'm fine

Turkey
(empty)

文本块可能有一行或多行,由一个或多个空行甚至日期而不是空白分隔。后者可以通过将日期替换为空行来解决。

想要的结果:

Cheese
I'm fine

Ham 
this is good 
(mind the mail)

Turkey 
(empty)

中显示的输出来看,您的行都以 control-Ms (Carriage Returns) 结尾,所以看起来是空的实际上不是,所以您的整个文件是一条记录当 RS 为空时。 运行 dos2unixsed 's/\r$//' 在您的输入文件上删除那些 CR,然后再次 运行 awk 命令。请参阅我 运行 对输入进行 sed 以删除 CR 前后的差异:

$ cat -Ev file
Ham  ^M$
this is good  ^M$
(mind the mail)^M$
^M$
Cheese  ^M$
I'm fine^M$
^M$
Turkey^M$
(empty)^M$

$ awk -v RS= '{print NR, "<" [=11=] ">"}' file | cat -Ev
1 <Ham  ^M$
this is good  ^M$
(mind the mail)^M$
^M$
Cheese  ^M$
I'm fine^M$
^M$
Turkey^M$
(empty)^M>$

$ sed 's/\r$//' file > tmp && mv tmp file

$ cat -Ev file
Ham  $
this is good  $
(mind the mail)$
$
Cheese  $
I'm fine$
$
Turkey$
(empty)$

$ awk -v RS= '{print NR, "<" [=14=] ">"}' file | cat -Ev
1 <Ham  $
this is good  $
(mind the mail)>$
2 <Cheese  $
I'm fine>$
3 <Turkey$
(empty)>$

有关这些 DOS 行结尾的更多信息,请参阅