1834448 Members
2691 Online
110067 Solutions
New Discussion

Re: previous line

 
SAM_24
Frequent Advisor

previous line

Hi,

I want to grep the line which contains word "connected" and print previous line.Any help is appreciated.

Thanks.
Never quit
5 REPLIES 5
Pete Randall
Outstanding Contributor

Re: previous line

SAM,

Here's a solution from the "Handy One-Liners for Sed" (attached):

# print 1 line of context before and after regexp, with line number
# indicating where the regexp occurred (similar to "grep -A1 -B1")
sed -n -e '/regexp/{=;x;1!p;g;$!N;p;D;}' -e h



Pete

Pete
Rodney Hills
Honored Contributor

Re: previous line

If you get the GNU grep command, it has an option "-B num" to print "num" lines before each line.

HTH

-- Rod Hills
There be dragons...
Michael Schulte zur Sur
Honored Contributor

Re: previous line

Hi,

something with awk:
BEGIN{ll="no previous line";}
/connect/ {print ll;print $0}
{ll=$0;}
END{}

use awk -f yourname.awk yourfile

greetings,

Michael
Elmar P. Kolkman
Honored Contributor

Re: previous line

If you want, it can even be done with a shell script:
grep -n connected | cut -d: -f1 | while read number
do
(( number=number-1 ))
sed -n "${number}p"
done

You could even use tail and head to get the line you want.
Every problem has at least one solution. Only some solutions are harder to find.
Elmar P. Kolkman
Honored Contributor

Re: previous line

Neater solution using shell:
grep -n connected | cut -d: -f1 | while read number
do
(( number=number-1 ))
echo "${number}p"
done | ed -

This way the file is opened twice instead of 1 plus the number of occurrences...
Every problem has at least one solution. Only some solutions are harder to find.