![grep 或其他正規表示式來取得輸出值](https://rvso.com/image/1576007/grep%20%E6%88%96%E5%85%B6%E4%BB%96%E6%AD%A3%E8%A6%8F%E8%A1%A8%E7%A4%BA%E5%BC%8F%E4%BE%86%E5%8F%96%E5%BE%97%E8%BC%B8%E5%87%BA%E5%80%BC.png)
如何使用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}'