【问题标题】:How to get line below second to last instance of a string in a file如何在文件中字符串的倒数第二个实例下方获取行
【发布时间】:2021-09-01 17:34:37
【问题描述】:

我正在尝试获取文件中字符串倒数第二个实例下方的行,但 tail +2 命令似乎无法找到倒数第二个实例。当我尝试下面的代码时:


for i in `find . -name "aims.out" -type f`;
do
     grep -l 'grep -A 1 "string"' $i
     T1=$(grep 'string' $i|tail +2)
     grep -l 'grep -A 2 "string"' $i
     T2=$(grep 'string' $i|tail +2)
    
done

我收到错误“tail: cannot open ‘+2' for reading: No such file or directory”,我得到了最后一个实例。有什么建议吗?

示例输入:

 | i_atom:           25
  | i_atom:           26
  |
 sum osc_str                     NaN
 n_elec   106.000000000000
  Eigenvalues TDA BSE.
  State    Eigenvalue [Ha]    Eigenvalue [eV]    Oscillator Strength
      1          -0.152200          -4.141573             NaN
      2          -0.136095          -3.703339             NaN
      3          -0.133551          -3.634100             NaN
      4          -0.128803          -3.504903             NaN
      5          -0.124969          -3.400571             NaN

样本输出:

-4.141573

编辑:解决

T1=$(cat aims.out| grep -A 1 "string" | tail -n 4 | head -n 1 | cut -c 36-46 )

【问题讨论】:

  • 请在您的问题中添加示例输入(无描述、无图像、无链接)以及该示例输入所需的输出(无评论)。
  • 试试tail -n +2。 tail --help 输出什么?
  • 在查看了一些帮助之后,我想出了一个解决方案。谢谢!

标签: bash grep instance tail


【解决方案1】:

要在模式foo 倒数第二次出现后打印该行,您可以这样做:

awk 'h{h=0; b=a; a=$0} /foo/ {h=1}END {print b}' input

要将其合并到 find 中,您可以这样做:

find . -name aims.out -type f -exec awk 'h{h=0; b=a; a=$0} 
    /string/ {h=1}END {print b}' {} \;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-17
    • 1970-01-01
    • 1970-01-01
    • 2012-12-05
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 2013-11-15
    相关资源
    最近更新 更多