Operating System - HP-UX
1833875 Members
1762 Online
110063 Solutions
New Discussion

Re: To get one line and the first in one file

 
SOLVED
Go to solution
Carme Torca
Super Advisor

To get one line and the first in one file

Hi,

I know how to get one line and the next,

#perl -ne '/text to match/ || next;print $_;if(not eof){$_=<>;print}' file

but how I do to get one line and the previous???

Thanks very much!!
Carmen.
Users are not too bad ;-)
6 REPLIES 6
Pete Randall
Outstanding Contributor

Re: To get one line and the first in one file

Carmen,

sed -n -e '/text_to_match/{=;x;1!p;g;$!N;p;D;}' -e h

will give you the previous and subsequent lines.


Pete

Pete
Carme Torca
Super Advisor

Re: To get one line and the first in one file

Hi,

I would like get for exemple:

1
caracol
2
3
4
caracol
5
6
7
caracol
8
9
caracol

If I look for 'caracol', I would like to get
1
caracol

4
caracol

7
caracol

9
caracol

Thanks!!
Carmen.

Users are not too bad ;-)
Muthukumar_5
Honored Contributor

Re: To get one line and the first in one file

We can do it as,
# cat > forum.log
1
caracol
2
3
4
caracol
5
6
7
caracol
8
9
caracol
# sed -n 'N;/caracol/p' forum.log
1
caracol
4
caracol
7
caracol

It will give your prev. line with respect to the pattern to you.
Easy to suggest when don't know about the problem!
Carme Torca
Super Advisor

Re: To get one line and the first in one file

Thanks,

But if I have this file, the sed doesn't works ok??

#more forum.log
hola
1
hola
6
2
hola
6
3
hola
4
6
7
8


# sed -n 'N;/hola/p' forum.log
hola
1
hola
6
2
hola
hola
4


??
Thanks!,
Users are not too bad ;-)
Cesare Salvioni
Trusted Contributor
Solution

Re: To get one line and the first in one file

hi
try this

awk '
BEGIN {line=""}
$0 ~ /pattern/ {print line}
{ line = $0 }
' < file

you can arrange the line whith the check and the print to reflect which kind of control you want. In the example it looks for a pattern in all the read line, but you can check only one field delimited by space ($1, $2, $3 etc.) or more of them or .... see man awk ;-))

hope it helps
Hein van den Heuvel
Honored Contributor

Re: To get one line and the first in one file


Carmen,

Please consider using 'search' before entering a new topic, as many 'obvious' questions have been asked an answerred (many times :-) before.

For this case, 'more options' + forum=hpux + words="previous lines" woudl quikly point to:


http://forums1.itrc.hp.com/service/forums/questionanswer.do?threadId=356066

Admittedly I had a hard time finding a reply backthat I recalled having solved a much similar problem:

http://forums1.itrc.hp.com/service/forums/questionanswer.do?threadId=524659

Here is my AWK 'one-liner' from there looking back for 'window' sized W-lines from a search pattern


awk 'BEGIN {W=4} {line[i++%W]=$0} /textt/{for (j=i-W;j
in sticking with your original question and PERL, one possible solution is:

perl -ne 'if (/text to match/) {print "$last$_"} else {$last=$_}' file

hth,
Hein.