正規表現の結果に基づいて入力ファイルをソートする

正規表現の結果に基づいて入力ファイルをソートする

正規表現の結果に基づいてファイルをソートしたいと思います。たとえば、Obj-Cに次の属性宣言がある場合

@property (nonatomic, strong) id <AlbumArtDelegate, UITextFieldDelegate> *albumArtView; // 1
@property (nonatomic, strong, readonly) UIImageView *profileView;  // 2
@property (nonatomic, strong, readwrite) UIButton *postFB;          // 3
@property (nonatomic, assign) UIButton *saveButton;      // 4

基本的には[4, 1, 2, 3]の順にソートされますが、実際の属性名である[1, 3, 2, 4]の順にソートしたいと思います。属性名だけを調べる正規表現を作成でき、その式の結果に基づいてソートできますか?

これを行うための組み込みのUnixツールはありますか?私はXcodeで作業しているので、VIM / emacsソリューションは役に立ちません。

また、正規表現を使用してこれを実行したいのは、他の状況でも機能するようにソートアルゴリズムを拡張できるためです。メソッド宣言、import文などをソートするために使用します。

ベストアンサー1

行内容の機能に基づいてソートする一般的な方法は次のとおりです。

  1. ソートするキーを取得し、行の先頭にコピーします。
  2. タイプ
  3. 行の先頭のキーの削除

この特別なケースでは、次のキーを使用できます。プログラムはsed最後の識別子から最後まで行を出力します。

% sed -e 's/^.*[^[:alnum:]_]\([[:alpha:]][[:alnum:]_]*\)/\1/' < decls

albumArtView; // 1
profileView;  // 2
postFB;          // 3
saveButton;      // 4

これらのキーを元の行と並べて配置するには、次の手順を実行します。

% paste <(sed -e 's/^.*[^[:alnum:]_]\([[:alpha:]][[:alnum:]_]*\)/\1/' < decls) decls

並べ替え...

| sort

2番目のフィールド(元の行)のみを保持します。

| cut -f 2-

すべてを整理すると(表示する内容があるように逆順に並べ替え):

% paste <(sed -e 's/^.*[^[:alnum:]_]\([[:alpha:]][[:alnum:]_]*\)/\1/' < decls) decls \
  | sort -r \
  | cut -f 2-

@property (nonatomic, assign) UIButton *saveButton;      // 4
@property (nonatomic, strong, readonly) UIImageView *profileView;  // 2
@property (nonatomic, strong, readwrite) UIButton *postFB;          // 3
@property (nonatomic, strong) id <AlbumArtDelegate, UITextFieldDelegate> *albumArtView; // 1

おすすめ記事