2

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

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.

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:

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Joe Jobs
  • 201
  • 1
  • 12

1 Answers1

4
awk '{print} /fox/{exit}' file

With GNU sed:

sed '0,/fox/!d' file

or

sed -n '0,/fox/p' file
Cyrus
  • 84,225
  • 14
  • 89
  • 153
  • Those scripts work great, how about deleting the lines after the last match of the word? Shall I ask another question for that? – Joe Jobs Dec 31 '20 at 21:56
  • Another question: How about deleting lines after match, including the matching line? In the example above, only the first line will be printed - "The quick" – Joe Jobs Dec 31 '20 at 22:05
  • Yes, I suggest to start a new question. – Cyrus Dec 31 '20 at 22:39
  • Great, I started the question here - https://stackoverflow.com/questions/65526188/delete-all-lines-after-the-last-match – Joe Jobs Dec 31 '20 at 23:23
  • I could not find the duplicate question by myself but now it's linked in the body of this question. Thans. How about the second question - delete lines after match, including matched line? – Joe Jobs Jan 01 '21 at 00:18
  • 1
    This should do the job: `awk 'NR==FNR{if (/fox/) hit=NR; next} FNR==hit{exit} {print}' file file` It's a smal modification to [this answer](https://stackoverflow.com/a/44309745/3776858). – Cyrus Jan 01 '21 at 00:21