Vijay Athreyan
Vijay Athreyan

Reputation: 425

Unix Sed to get lines from a last occurance of a given word

I want to get the lines from a file from the line which contains the last occurance of a given word.

Ex:

True, there have been some
changes in the plot. In the original,
Kane tried to buy high political
office for himself. In the new version,
he just puts politicians on his payroll.

If I give "In" then I need

office for himself. In the new version,
he just puts politicians on his payroll.

Upvotes: 2

Views: 4375

Answers (4)

loganaayahee
loganaayahee

Reputation: 819

I can print the 4th line and end of line only

My command is

sed -n '4,$p' file

Upvotes: 0

Dennis Williamson
Dennis Williamson

Reputation: 359965

This should work:

As a one-liner:

patt=In
sed -nr "/$patt/!b;:a;\$!N;/\n.*$patt/{h;s/\n[^\n]*\$//;g;s/^.*\n//};\$!ba;p" inputfile

If your sed requires -e:

patt=In
sed -nr -e "/$patt/!b" -e ":a" -e "\$!N" -e "/\n.*$patt/{h" -e "s/\n[^\n]*\$//" -e "g" -e "s/^.*\n//}" -e "\$!ba" -e "p" inputfile

On separate lines:

patt=In
sed -nr "
    /$patt/!b
    :a
    \$!N
    /\n.*$patt/{
    h
    s/\n[^\n]*\$//
    g
    s/^.*\n//
    }
    \$!ba
    p' inputfile

Upvotes: 0

eumiro
eumiro

Reputation: 212835

Try:

grep 'yourWord' yourFile.txt | tail -n1

Or with sed:

sed -n '/yourWord/{$p}' yourFile.txt

Upvotes: 1

ghostdog74
ghostdog74

Reputation: 342323

$ word="In"
$ awk -vw="$word" '{s=s$0}END{ m=split(s,str,w); print w str[m]}' file
In the new version, he just puts politicians on his payroll.

I don't understand why there is "office for himself." though.

Upvotes: 0

Related Questions