Bash脚本文件读取

时间:2014-09-02 16:11:21

标签: bash file for-loop

我正在尝试从输出文件中选择某些文本。

我正在阅读我的文件如下:

while read line 
do
    if [ "$line" == "SUMMARY OF POLARIZATION CALCULATION" ]; then
        break
    fi
done < tutorial1/Tutorial1_1.out

当循环到达“Summary”行时,我只需要读取接下来的9行。我正在尝试使用for循环,但我不确定如何使用它:

for i in {1..9}
do
    read line < tutorial1/Tutorial1_1.out
    echo $line >> Summary.out
done

我的输出如下:

next is setrmt
next is setrmt
next is setrmt
next is setrmt
next is setrmt
next is setrmt
next is setrmt
next is setrmt
next is setrmt

但我需要它成为“SUMMARY”声明之后的下一行9行。请帮忙。

3 个答案:

答案 0 :(得分:3)

您可以使用-A命令的grep参数,如:

grep -A9 "SUMMARY OF POLARIZATION CALCULATION"

来自男人:

  

-A NUM, - after-context = NUM​​

          Print NUM lines of trailing context after matching lines.

演示:

while read -r line
do
    echo "$line"
done < <(grep -A9 "SUMMARY OF POLARIZATION CALCULATION" filename | tail -9)

用于下一个输入文件

before1
before2
before3
before4
before5
before6
SUMMARY OF POLARIZATION CALCULATION
line1
line2
line3
line4
line5
line6
line7
line8
line9
line10
line11
line12

打印:

line1
line2
line3
line4
line5
line6
line7
line8
line9

或简单地说:

 grep -A9 "SUMMARY OF POLARIZATION CALCULATION" ../Tutorial1_1.out | tail -9 >> Summary.out

答案 1 :(得分:2)

您无法再次重定向。这会在开头重新打开文件。在第一个块内部执行第二个块并使用相同的文件描述符:

while read line 
do
    if [ "$line" == "SUMMARY OF POLARIZATION CALCULATION" ]; then
        for i in {1..9}
        do
            read line
            echo $line >> Summary.out
        done
        break
    fi
done < tutorial1/Tutorial1_1.out

答案 2 :(得分:0)

让我们尝试一个干净的解决方案:

1)找到包含所需字符串的行的行号。你可以通过实现一个计数器来做到这一点,但这更好:

linenr=$(grep -n -m 1 "SUMMARY OF POLARIZATION CALCULATION" <your file name here> | cut -d':' -f1)

2)计算你想要的最后一行的数量:

let "lastlinenr = $linenr + 9"

3)获取行并将其写入文件:

cat <your file name here> | sed -n "$linenr","$lastlinenr"p > <your destination file here>