Linux
僅列印與 awk 匹配後的最後一行
我有一個命令,它使用不同的工具(如
grep
、awk
和tail
. 這可行,但感覺有些混亂,並使用多個管道來完成此任務。是否可以僅使用其中一種工具在一個命令中執行此操作?文件末尾還有一行空格。文件內容:
10:28:48 2022-09-15T15:28:36Z: Creating tar ball for build artifacts -- 10:28:53 --> Build complete: Artifacts were created: file: build-1.tar.gz
命令
grep -A1 "Artifacts were created:" $file | tail -n1 | awk '{print $2}'
結果
build-1.tar.gz
這在技術上有效,但似乎有點草率。
請試試:
awk '/Artifacts were created:/{p=1} NF{out=$2} END{if(p==1){print out}}' infile
儘管您提供的管道是在匹配之後提取該行的第二個欄位,而不是最後一個。這可以轉換為對 awk 的一次呼叫:
awk ' # Have we found the match? /Artifacts were created:/{ found=1 ; next } # if a match has been found, capture the second field # and reset the found flag to avoid capturing other line. found==1{out=$2;found=0} # All lines have been processed, # print either the value or an empty line. END{print out} ' "$file"