Bashの文字列に一致する行の並べ替え

Bashの文字列に一致する行の並べ替え

前のコマンドの出力は次のとおりです。

foo 1 some-string
    P another-string
bar 5 and-another-string

P別の行を順番に維持しながら、前/後に1つ以上のスペースを含むすべての行を一番上に移動したいと思います。たとえば、次のようになります。

    P another-string
foo 1 some-string
bar 5 and-another-string

行数が不明です。可能であれば、通常のbashまたはsed

ベストアンサー1

sed -n '
/ P /p   #If line contains " P ", print it
/ P /!H  #Else, append it to hold space
${       #On last line
  x      #Exchange hold space with pattern space
  s|\n|| #Remove first extra newline
  p      #Print
}' file

同じ単一コード行を使用した実行例:

$ cat file
foo 1 some-string
    P another-string
bar 5 and-another-string
APstring
    A P string
ipsum
ARP
    P VC
$ sed -n '/ P /p;/ P /!H;${x;s|\n||;p;}' file
    P another-string
    A P string
    P VC
foo 1 some-string
bar 5 and-another-string
APstring
ipsum
ARP

おすすめ記事