Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
354 views
in Technique[技术] by (71.8m points)

search - Remove lines after first match

I need to remove all lines after the first line that contains the word "fox"

Say for example for the following input file "in.txt"

The quick
brown fox jumps
over
the
lazy dog
the second fox
is hunting

The result will be

The quick
brown fox jumps

I prefer a script made in awk or sed but any other command line tools are good, like perl or php or python etc.

For searching purposes I will add this line:

Remove lines after occurrence

Later edit:

I am using gnuwin32 tools in Windows, and the solution I could find was this one:

grep -m1 -n fox in.txt | cut -f1 -d":" > var.txt
set /p MyNumber=<var.txt
head -%MyNumber% in.txt > out.txt

However, I am looking for a solution that is shorter and that is portable (this one contains Windows specific command "set /p"

Similar questions:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
awk '{print} /fox/{exit}' file

With GNU sed:

sed '0,/fox/!d' file

or

sed -n '0,/fox/p' file

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...