
次のような内容のファイルがある場合:
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など)を使用して、各3行のグループでインデントされていない最初の行に基づいてファイルをアルファベット順に並べ替えると同時に、既存のグループの下にインデントされた行を保持できますか?
答え1
Perlでは、次のことができます。
- ツバメファイル(
perl -0n
) - インデントされていない行に入力を分割する
split(/^(?=\S)/m)
- 並べ替えと印刷
perl -0ne 'print sort split(/^(?=\S)/m) ' ex
答え2
<EOL>
まず、sedはテキストをセクション行間の区切り文字として使用して、各セクションを1行に配置します。その後、セクションをソートし、2番目の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"]
:要素を使用して必要なソートタイプを設定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