使用 awk 或 sed 从末尾查找第一次出现

Jac*_*ife 3 awk sed

是否可以使用awk或从文件末尾找到第一个字符串出现sed?或者我需要使用一些脚本语言,比如 Python 或 Perl?

hek*_*mgl 6

您可以使用tac(与 的相反cat)恢复文件中的行顺序,然后使用grep

tac file | grep -m 1 STRING
Run Code Online (Sandbox Code Playgroud)

grep -m1 只给你第一次出现。

或者,您可以直接通过管道grep发送至tail

grep STRING | tail -n1
Run Code Online (Sandbox Code Playgroud)

如果你想使用awk

awk 'BEGIN{res=""}/STRING/{res=$0}END{if(res!=""){print res}}' file
Run Code Online (Sandbox Code Playgroud)

解释:

# Initialize result with an empty string
BEGIN{res=""}
# If STRING is found, store the current line in res.
# This will overwrite a previous result, giving you
# always only the last occurrence.
/STRING/{res=$0}
# Once the end of input has been reached print the result
# if STRING was found.
END{if(res!=""){print res}}
Run Code Online (Sandbox Code Playgroud)