S
S
stcmd042362017-03-11 18:33:02
linux
stcmd04236, 2017-03-11 18:33:02

How to get the first and last lines that matches a given word in bash?

There is a file log. How to get the string of first and last occurrence for a given word?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry, 2017-03-11
@stcmd04236

Offhand

$ cat 1.txt
1 line
2 line
3 bar
4 line
5 line
6 line
7 foo
8 line
9 line
$ grep line 1.txt | sed -n '1p;$p' -
1 line
9 line

True, if there is only one entry from grep, then one line will be displayed twice.
In general, learn to google.
grep line 1.txt | sed '1!{$!d}'

F
fdrwitch, 2017-03-12
@fdrwitch

if manually, and too lazy to look at sed, then you can simply:
grep line -n ​​ttt.txt | head -1
grep line -n ​​ttt.txt | tail -1
grep is given a numbered pattern, and you take the first and last occurrences, respectively, for the head and tail

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question