
如果我有一個內容類似以下內容的文件:
FirstSection
Unique first line in first section
Unique second line in first section
SecondSection
Unique first line in second section
Unique second line in second section
...
NthSection
Unique first line in Nth section
Unique second line in Nth section
是否可以使用unix命令(例如sort、awk)按每三行組中的第一個非縮進行的字母順序對文件進行排序,同時將縮進行保留在現有組下?
答案1
使用 Perl,您可以運行以下內容:
- 吞嚥文件 (
perl -0n
) - 透過不縮排的行分割輸入
split(/^(?=\S)/m)
- 排序並列印
perl -0ne 'print sort split(/^(?=\S)/m) ' ex
答案2
首先 sed 將每個節放在一行上,並使用文字<EOL>
作為節行之間的分隔符號。然後我對這些部分進行排序並使用第二個 sed 將每個<EOL>
部分恢復為換行符。
sed -r ':r;$!{N;br};s:\n([[:blank:]])(\1*):<EOL>\1\2:g' file|sort|sed -r '/^$/d;:l;G;s:(.*)<EOL>(.*)(\n):\1\3\2:;tl;$s:\n$::'
我沒有選擇字元作為分隔符,因為輸入檔案可能有它,所以我使用了它<EOL>
。
輸出:我在每個部分(最後一個部分除外)後面添加了一個換行符,以重新建立輸入檔案的樣式。
FirstSection
Unique first line in first section
Unique second line in first section
NthSection
Unique first line in Nth section
Unique second line in Nth section
SecondSection
Unique first line in second section
Unique second line in second section
答案3
awk
使用GNU asort()
,PROCINFO["sorted_in"]
我們可以根據每組之間的換行符將每組記錄保存到一個awk關聯數組中;然後使用asort()
for 循環對數組進行排序並列印所有組。
awk '/^$/{ ++grpNr; next }
{ groups[grpNr]=(groups[grpNr]==""? "" : groups[grpNr] RS) $0 }
END{ asort(groups);
for(grp in groups) print groups[grp]
}' infile
筆記:您可以使用PROCINFO["sorted_in"]
element來設定您需要哪種類型的排序;例如PROCINFO["sorted_in"]="@val_str_desc"
將排序瓦爾我們的數組的 ue 為斯特ing 和 in描述命令。
或使用any awk
(產生 Nul 分隔的記錄區塊)+ sort -z
(根據 Nul 字元而不是換行符進行排序)+ tr
(透過 刪除先前新增的 Nul 字元awk
):
<infile awk '/^$/{ ++grpNr; next }
{ groups[grpNr]=(groups[grpNr]==""? "\0" : groups[grpNr] RS) $0 }
END{ for(grp in groups) print groups[grp] }' |sort -z |tr -d '\0'
對輸入檔進行測試,例如:
BFirstSection
Unique first line in first section
Unique second line in first section
DSecondSection
Unique first line in second section
Unique second line in second section
Aanothersection...
...
...
CfourthSection
Unique first line in Nth section
Unique second line in Nth section
您將得到如下輸出:
Aanothersection...
...
...
BFirstSection
Unique first line in first section
Unique second line in first section
CfourthSection
Unique first line in Nth section
Unique second line in Nth section
DSecondSection
Unique first line in second section
Unique second line in second section