Linux

與 awk 匹配後僅列印下一行

  • September 28, 2022

我有一個命令,它使用不同的工具(如grepawktail. 這可行,但感覺有些混亂,並使用多個管道來完成此任務。是否可以僅使用其中一種工具在一個命令中執行此操作?文件末尾還有一行空格。

文件內容:

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, print and exit
     found == 1 { print $2; exit }

   ' "$file"

如果sed是一個選項

$ sed -En '/Artifacts were created:/{n;s/[^ ]* (.*)/\1/p}' <<< "$file"
build-1.tar.gz

引用自:https://unix.stackexchange.com/questions/718913