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

使用 perl,您可以執行以下操作。它捕獲minimum:塊內之後的數值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

慢動作:

  • -r告訴sed我們使用擴展的正規表示式“語法”
  • -n告訴sed不要列印不匹配的行
  • s/^\s+Minimum:\s+([0-9.]+).+$/\1/匹配您的目標行並將其替換為您想要的值
  • p告訴sed列印結果

如果您需要透過考慮前面幾行的內容來消除歧義,則情況會稍微複雜一些:

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:」在您的輸入中只出現一次:

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

相關內容