如何根据某些字符串提取行和之前的行

How to extract a line and a line before that based on certain strings

我正在尝试提取包含特定字符串的行以及它之前的 4 行(只是第四行而不是中间的行)。现在我可以得到这条线了;

grep -n "my string" myfile.out > output.txt

我也能得到它前面的几行,但不是那个特定的那一行,所有前面的四行;

grep "my string" -B 4 myfile.out > output.txt

举个例子:

 ! CREEK                                                              
 FLUX 6739, 6670, 6640, 6672, 6582, 6583, 6548, 6576, 6570 &      
 656565                   
 ***
 ***  THE SUM OF SPECIFIED:   -1.192451    
 ***  THE AVERAGE:  -6.2760599E-02
 ***  THE MAXIMUM:    0.000000    
 ***  THE MINIMUM:  -0.4294980    
 ***  THE SUM OF POSITIVE:    0.000000    
 ***  THE SUM OF NEGATIVE:   -1.192451   

我想要这个输出:

 ! CREEK
 ***  THE SUM OF SPECIFIED:   -1.192451

我将不胜感激 windows-批处理文件解决方案或 PowerShell。

如果您的文件名为 myfile.out,这应该可以满足您的要求:

grep "THE SUM OF SPECIFIED" -B 4  myfile.out | sed -n "1p;5p"

这是tac + awk解决方案:

tac file |
awk '/THE SUM OF SPECIFIED/{p=NR; print} p && NR==p+4{print; p=0}' |
tac

! CREEK
***  THE SUM OF SPECIFIED:   -1.192451

或者这里是grep + awk解决方案:

grep "THE SUM OF SPECIFIED" -B 4 file | awk 'NR==1 || NR ==5'

Poweshell 解决方案:

# verbose version 
Select-String "THE SUM OF SPECIFIED" -Path "C:\temp\test.txt" -Context 4,0 | foreach { $_.Context.PreContext[0]; $_.Line}

# or short version (with alias)
sls "THE SUM OF SPECIFIED" "C:\temp\test.txt" -Co 4,0 | % { $_.Context.PreContext[0]; $_.Line}