![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Newbie
Join Date: Jul 2004
Posts: 8
Rep Power: 0
![]() |
Hi
Is there any way with grep to show me only the last pattern that matches and not all ? For example for a file with linux 56 slackware 32 debian 34 linux 2 redhat 9 and $> grep linux filename show me only --> linux 2 and not linux 56 linux 2 Thanks |
|
|
|
|
|
#2 |
|
Programmer
Join Date: Sep 2004
Posts: 38
Rep Power: 0
![]() |
Hmm, bit tricky - you could do it with awk (and maybe sed) - but I'm not sure how to do it with grep.
Here is a perl one liner that will do it though. $ perl -ne 'next unless (/linux/); $v = $_; { END { print $v } }' foo.txtIf you really have to do it with just shell tools just use awk to do pretty much the same thing that perl one liner does, overwrite a variable with each line that matches the pattern and have an END statement print the variable. |
|
|
|
|
|
#3 |
|
Programmer
|
Nice oneliner, bro. Overkill, but very nice... I could crank out an awk version, but it would be too similiar to that one, and it just does the job well enough. If you want it to run a little bit faster, try this:
$ grep "linux" foo | tail -1
__________________
<span style='font-size:14pt;line-height:100%'><span style='color:red'>"Political power grows out of the barrel of a gun" - Mao Tse-Tung</span></span> |
|
|
|
|
|
#4 |
|
Programmer
Join Date: Sep 2004
Posts: 38
Rep Power: 0
![]() |
Doh! Yeah 'tail' is a much simpler and faster way to do it.
-but you can never have too much overkill ![]() |
|
|
|
|
|
#5 |
|
Programmer
|
I really thought the awk solution to this would look the same or atleast very similiar. Little did I know that because of the lack of $_ in awk, I had to do a little research. This is a little bit more light-weight than the perl version above, but since perl is the all-in-one swiss army chainsaw, they go hand-in-hand depending on what you do:
$ awk '/linux/ { last = $0 }; END { print last }'foo
__________________
<span style='font-size:14pt;line-height:100%'><span style='color:red'>"Political power grows out of the barrel of a gun" - Mao Tse-Tung</span></span> |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|