grep または他の正規表現を使用して出力の値を取得します

grep または他の正規表現を使用して出力の値を取得します

grep出力で特定の値を取得するために、またはその他のツールを使用する方法

255.00以下の出力では、次の行の値を取得する必要があります。Minimum: 255.00 (1.0000)

次のようなパターン:Channel Statistics:\s+Gray:\s+Minimum: +([\d.]+)

Image: test.tif
  Format: TIFF (Tagged Image File Format)
  Geometry: 2525x1785
  Class: DirectClass
  Type: bilevel
  Depth: 1 bits-per-pixel component
  Channel Depths:
    Gray:     1 bits
  Channel Statistics:
    Gray:
      Minimum:                   255.00 (1.0000)
      Maximum:                   255.00 (1.0000)
      Mean:                      255.00 (1.0000)
      Standard Deviation:          0.00 (0.0000)
  Filesize: 581
  Interlace: No
  Orientation: Unknown
  Background Color: white
  Border Color: #DFDFDF
  Matte Color: #BDBDBD

答え1

minimum:perl を使用すると、次の操作を実行できます。ブロック内の後の数値をキャプチャしてChannel Statistics:出力します。

perl -0 -ne '/Channel Statistics:\s+Gray:\s+Minimum:\h+([\d.]+)/ && print $1,"\n"' file

出力:(例)

255.00

説明:

-0      # specifies the input record separator. If there are no digits, the null character is the separator. The whole file is read in a single string.
-n      # Iterate over the file
-e      # execute the command line

正規表現:

/                           # regex delimiter
    Channel Statistics:     # literally
    \s+                     # 1 or more any kind of spaces
    Gray:                   # literally
    \s+                     # 1 or more any kind of spaces
    Minimum:                # literally
    \h+                     # 1 or more horizontal spaces
    (                       # start group 1
        [\d.]+              # 1 or more digit or dot
    )                       # end group
/                           # regex delimiter

答え2

sed

sed -rn 's/^\s+Minimum:\s+([0-9.]+).+$/\1/p' image.data

スローモーション:

  • -rsed拡張正規表現「構文」を使用するように指示します
  • -nsed一致しない行を印刷しないように指示する
  • s/^\s+Minimum:\s+([0-9.]+).+$/\1/ターゲット行と一致し、必要な値に置き換えます
  • psed結果を印刷するように指示する

前の行の内容を考慮して曖昧さを解消する必要がある場合は、少しだけ複雑になります。

sed -r ':a;N;$!ba; s/^.*Gray:\s*\n\s+Minimum:\s+([0-9.]+).+$/\1/' image.data

どこ:

  • :a;N;$!ba;言語のループでsed、ファイル全体を一度にロードします。
  • -n印刷したくない行が他にないので、これはもう必要ありません。
  • 最終句pも不要になりました。-n

答え3

これは非常に単純化されており、入力内に文字列「Minimum:」が 1 回だけ出現することを前提としています。

awk '/Minimum:/ {print $2}'

関連情報