We help IT Professionals succeed at work.

Read a file using shell scripts(using bash not perl)

mahanteshs
mahanteshs asked
on
I want to read  a file from last occurence of a specific pattern till end of file

Eg:-
a1.h is

#include "EncryptString.h"
#include "stdafx.h"
CString Start_Encryption(CString);
1.5
CString encrypt_phase1(CString);
1.7
CString encrypt_phase2(CString);
1.5
CString encrypt_ascii(CString);
CString encrypt_reverse(CString);

I want to read lines from last occurence of 1.5 till the
end of file

ie
1.5
CString encrypt_ascii(CString);
CString encrypt_reverse(CString);

OR

Is there any work around to read a file in reverse order
So that I can read all the lines till the first occurence a particular patern

ie
CString encrypt_reverse(CString);
CString encrypt_ascii(CString);
1.5

thank U
mahant

Comment
Watch Question

Commented:
The 'tac' command will output the lines of a file in reverse order ( but the characters in each line will not be reversed). 'sed' can select the lines. Something like this should work:

>> tac myfile | sed -e '/<pattern>/,&d' > outputfile

The <pattern> is a regex expression (man 7 regex) but also check 'man sed' and 'info sed' since some 'sed' programs have special extensions to regex

Commented:
What about the following

grep -A`wc -l $1 | awk '{print $1}'` $2 $1

This is called using the format script filename search_text

It works out how many lines are in the file (the wc -l and awk bit) then greps for the search text and displays all the lines after the match.

Cheers - Gavin

BRONZE EXPERT

Commented:
grep -n "" file|grep -A`wc -l file|awk '{print $1}'` `grep -n pattern file|awk '{n=$1}END{print n}'`|sed -e 's/^[0-9][0-9]*://'

# not as elegant as tac, but works always, anywhere ..
#
# NOTE: depending on the pattern, you probably need to quote it appropriate

Author

Commented:
Hello I got the solution using tac command & sed

Thank U MFCRich also I would like to thank newmang & ahoffmann for letting me know the alternative ways.


regards,
mahantesh.
jmcgOwner
BRONZE EXPERT

Commented:
No comment has been added lately, so it's time to clean up this TA.
I will leave the following recommendation for this question in the Cleanup topic area:

Accept: MFCRich {http:#6707511}

Please leave any comments here within the next seven days.
PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!

jmcg
EE Cleanup Volunteer

Explore More ContentExplore courses, solutions, and other research materials related to this topic.