grep从文件开头到包含字符串的行的所有行

时间:2011-02-19 06:33:16

标签: command-line grep

如果我有包含

的输入文件
statementes
asda
rertte 
something 
nothing here 

我想grep / extract(不使用awk)从开始直到我得到字符串“something”的每一行。我怎样才能做到这一点? grep -B不起作用,因为它需要确切的行数。

期望的输出:

statementes
asda
rertte 
something 

3 个答案:

答案 0 :(得分:2)

它并不完全健壮,但确定-B可以工作......只需使-B计数巨大:

grep -B `wc -l <filename>` -e 'something' <filename>

答案 1 :(得分:0)

你可以使用bash while循环并在你点击字符串时提前退出:

$ cat file | while read line; do
> echo $line
> if echo $line | grep -q something; then
> exit 0
> fi
> done

答案 2 :(得分:0)

head -n `grep -n -e 'something' <filename> | cut -d: -f1` <filename>
相关问题