使用awk或sed从末尾查找第一个匹配项
是否可以使用使用awk或sed从末尾查找第一个匹配项,awk,sed,Awk,Sed,是否可以使用awk或sed从文件末尾查找第一个字符串?或者我需要使用一些脚本语言,如Python或Perl?您可以使用tac(与cat相反)还原文件中的行顺序,然后使用grep: tac file | grep -m 1 STRING grep-m1只提供第一次出现 或者,您可以通过管道将grep连接到tail: grep STRING | tail -n1 如果要使用awk: awk 'BEGIN{res=""}/STRING/{res=$0}END{if(res!=""){print
awk
或sed
从文件末尾查找第一个字符串?或者我需要使用一些脚本语言,如Python或Perl?您可以使用tac
(与cat
相反)还原文件中的行顺序,然后使用grep
:
tac file | grep -m 1 STRING
grep-m1
只提供第一次出现
或者,您可以通过管道将grep
连接到tail
:
grep STRING | tail -n1
如果要使用
awk
:
awk 'BEGIN{res=""}/STRING/{res=$0}END{if(res!=""){print res}}' file
说明:
# 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}}
使用sed
sed -n '/string/h;${x;p}' infile
使用awk
tac infile | awk '/abc/{print;exit}'
测试结果:
akshay@db-3325:/tmp$ cat infile
abc 1
xyz 2
pwd 3
cwd 4
aks 5
axy 6
abc 7
xyz 8
nwd 9
akshay@db-3325:/tmp$ sed -n '/abc/h;${x;p}' infile
abc 7
akshay@db-3325:/tmp$ tac infile | awk '/abc/{print;exit}'
abc 7
下面的
tac
和awk
组合将帮助您快速读取任何字符串的第一次出现
tac Input_file | awk '/STRING/{print;exit}'
说明:
tac
将反转输入文件,然后awk
将检查字符串,一旦收到,它将打印该行并退出,由于您只为第一次出现而烦恼,因此无需在此处阅读整个输入文件。请将示例输入文件和预期的代码标记输出发布到您的帖子中。@RavinderingH13任何以EML格式转发多次的电子邮件。我想提取原始信息。我们发现,EML文件底部的第一个返回路径:
表示原始消息。如果您能给出一个示例(您可以隐藏实际情况),请帮助我们理解需求。请原谅,我发现回答比搜索副本更容易。:)但这绝对是重复的。完美的例子!不客气:)我最终得到了代码tac$file | sed-n'1,/^返回路径:/p;''sed-ne“/^--$wrapping_boundary/d;p“| tac>out/$file
为我辩护,我没有从这里复制awk
解决方案,似乎我们的时间安排几乎相同:)