【问题标题】:Find first occurrence from the end with awk or sed [duplicate]使用 awk 或 sed 从末尾查找第一个出现 [重复]
【发布时间】:2018-01-18 16:08:50
【问题描述】:

是否可以使用awksed 从文件末尾找到第一个字符串?或者我需要使用 Python 或 Perl 等脚本语言?

【问题讨论】:

  • 请将示例 Input_file 和代码标签中的预期输出发布到您的帖子中。
  • @RavinderSingh13 任何多次转发的 EML 格式的电子邮件。我想提取原始消息。它出现在 EML 文件底部的第一个 Return-Path: 表示原始消息。
  • 如果你能给出一个示例(你可以隐藏实际的东西),这将有助于我们理解需求。
  • 原谅我,我发现回答比搜索副本更容易。 :) 但是,这绝对是重复的。

标签: awk sed


【解决方案1】:

您可以使用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}}

【讨论】:

  • 完美的例子!
  • 不客气 :)
  • 我得到了那个代码tac $file | sed -n '1,/^Return-Path:/p;' | sed -ne "/^--$wrapping_boundary/d;p" | tac > out/$file
【解决方案2】:

使用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

【讨论】:

  • 为我辩护,我没有从这里复制awk 解决方案,看来我们的时间几乎相同:)
【解决方案3】:

按照tacawk 组合将帮助您非常快速地读取任何字符串的第一次出现。

tac Input_file | awk '/STRING/{print;exit}'

解释: tac 将反转 Input_file 然后 awk 将检查字符串,一旦它得到它将打印该行并退出, 因为只关心第一次出现所以不需要在这里读取整个 Input_file。

【讨论】:

    猜你喜欢
    • 2015-06-08
    • 1970-01-01
    • 2015-12-03
    • 2017-11-11
    • 1970-01-01
    • 1970-01-01
    • 2014-12-04
    • 1970-01-01
    • 2019-11-19
    相关资源
    最近更新 更多