Extracting the last occurence

Hi All,

Is there any awk or unix command that i can make use such that the output will be as desired ?
The code will extract the latest pattern starting from the term above the asterix till the end of the input

Input:


aaa bbb 2007
********
123
234
134
********
xxx yyy 2007
********
aaa
bbb
cccc
dd
********
aaa bbb 2007
********
mmm
kkkkk
pppppp
ccccccc

Output:

aaa bbb 2007
********
mmm
kkkkk
pppppp
ccccccc

sed -n -e ":a" -e "N;/\naaa bbb/s/.*\n//;$ p;b a" file

With GNU Awk:

awk --re-interval '{x[NR]=($0 RT)}END{printf "%s\n%s\n",x[NR-1],$0}' RS="[*]{8}\n" inputfile

Or with nawk:

nawk '{sub(/\n/,"");x[NR]=$0}END{printf "%s********\n%s",x[NR-8],x[NR]}' RS="*" inputfile

Hi All,

Looks very complicated, but it works.
Any simplier method like using the command "cut" ?

You cannot do what do you want with cut command

Actually,

I have a code below and i believe it will work but i do not know what's the syntax error. Can you help >?

{if( NF == "2007" ) LINE = $0;}
END{printf("%20s\n",LINE); }

NF means number of fields in a row and it is an integer. What are you trying to do?

Hi anbu
please can you explain me the command you have written

********
aaa bbb 2007
********
123
234
134
********
xxx yyy 2007
********
aaa
bbb
cccc
dd
********
aaa bbb 2007
********
mmm
kkkkk
pppppp
ccccccc
sed -n -e ":a" -e "N;/\naaa bbb/s/.*\n//;$ p;b a" file 

"" is in pattern space.
N causes to read next line and append it to pattern space and now pattern space has "
\naaa bbb 2007" with embedded newline character.
Now substitute command removes "********\n" in pattern space.
b a causes to branch control to label ":a". N causes to read next line and append it to pattern space.
This is continued till it reaches line "aaa bbb 2007". Once this line is reached substitue command removes all the lines before this line.
$ p when the last line is reached it will print the contents in pattern space

Raynon,
Here is a program written in shell.
If you know shell and programming logic, it is easy to understand:

typeset -i StarLines=0
SearchStr='aaa bbb 2007'
Stars='********'
ToPrint='N'
while read ILine
do
 if [ "${ILine}" = "${Stars}" ]; then
   StarLines=$StarLines+1
   if [ ${StarLines} -eq 3 ]; then
     StarLines=1
   fi
   if [ ${StarLines} -eq 1 ]; then
     ToPrint='N'
     continue
   fi
 fi
 if [ ${StarLines} -eq 1 ]; then
   if [ "${ILine}" = "${SearchStr}" ]; then
     ToPrint='Y'
     echo "======== Starting a new string ==========="
   fi
 fi
 if [ ${ToPrint} = 'Y' ]; then
   echo "$ILine"
 fi
done < input_file