sedとsortを使用して2つのタグ間のテキストを取得し、アルファベット順に並べ替えるにはどうすればよいですか?

sedとsortを使用して2つのタグ間のテキストを取得し、アルファベット順に並べ替えるにはどうすればよいですか?

私は次のことをしたいと思います:

  1. 2つのタグ間のすべてのテキストを取得します。someFile.txt
  2. テキストを次のように分割された配列に配置します。\n
  3. 配列をアルファベット順に並べ替える
  4. 2つのタグ間のテキストをsomeFile.txtアルファベットバージョンに置き換えます。

someFile.txt操作前:

// __MARKER__
../library/_shared/_shared/components/InfoPill/InfoPill.stories
../library/_shared/_shared/components/IconChevronRightBlack/IconChevronRightBlack.stories
../library/_shared/_shared/components/ButtonPrimary/ButtonPrimary.stories
// __MARKER__

someFile.txt操作後:

// __MARKER__
../library/_shared/_shared/components/ButtonPrimary/ButtonPrimary.stories
../library/_shared/_shared/components/IconChevronRightBlack/IconChevronRightBlack.stories
../library/_shared/_shared/components/InfoPill/InfoPill.stories
// __MARKER__

ベストアンサー1

大丈夫perlで、ファイルがメモリ要件を満たすのに十分小さい場合

$ perl -0777 -pe 'BEGIN{$m = "// __MARKER__\n"}
                  s|$m\K.*?(?=\n$m)|join "\n", sort split/\n/,$&|gse' ip.txt 
// __MARKER__
../library/_shared/_shared/components/ButtonPrimary/ButtonPrimary.stories
../library/_shared/_shared/components/IconChevronRightBlack/IconChevronRightBlack.stories
../library/_shared/_shared/components/InfoPill/InfoPill.stories
// __MARKER__
  • -0777ファイル全体を文字列として読み込みます。
  • $m = "// __MARKER__\n"タグを変数に保存
  • $m\K.*?(?=\n$m)タグ間の文字列の取得
  • join "\n", sort split/\n/,$&キャプチャされた文字列を分割\nしてソートし、最後に配列要素を連結して単一の文字列を取得します。
  • s.一致する修飾子を受け入れます。\n
  • eセクションのコード置換を許可する修飾子
  • -i内部編集オプションの使用

おすすめ記事