how Print previous line ..........

HELLO...I wanted to ask you, than sure know unix more than me, as I can obtain the following solution: I have a file with rows of the type:

CIAO COME STAI
PERCHE COME STAI
CIAO COME VA
ALLO CHE FACCIAMO
.................

I would that if in a line is present the word (for example) " CHE " then i can print in video the previous three lines at the word "CHE" obtaining therefore:
CIAO COME STAI
PERCHE COME STAI
CIAO COME VA

As shell i use the KORN SHELL...thanks a lot and sorry for my bad english...

Using ksh, bash, ...

#!/bin/ksh
# script
l1=""
l2=""
l3=""
while read line
do
     case "$line" in
        *" CHE"*) echo "$l1"
                     echo "$l2"
                     echo "$l3"
                     l1=""  l2=""  l3=""
                    continue
                    ;;
     esac
     l1="$l2"
     l2="$l3"
     l3="$line"
done
chmod a+rx script
cat somefile | ./script
grep -B3 'CHE' file |grep -v 'CHE'

This should do you:

#  awk '
/ CHE / { for (x=1;x<4;x++){print t[NR-x]}}
{t[NR]=$0}
' infile

HTH

A Perl solution, just for completeness:

perl -ne 'BEGIN{ @a=("","",""); } print @a if /\bCHE\b/; push @a, $_; shift @a;' infile

-B3 is not so usable in all *nix.

grep

  • B3, Gnu extension - my quess.
awk -v v="CHE" '{_[NR]=$0}{for(x=0;x++<NF;)if($x==v){for(y=4;--y;) print _[(NR-y)];printf "\n"}}' file

thanks a lot for the help...a last question..it's possible to set the external variable of this case :

awk -v v="CHE" '{_[NR]=$0}{for(x=0;x++<NF;)if($x==v){for(y=4;--y;) print _[(NR-y)];printf "\n"}}' file
 

from the keybord across the function READ?....

From jmc: next time use code tags [ c o d e ] your code here [ / c o d e ] (remove spaces to make tags work).

read var
awk -v v="$var" '{_[NR]=$0}{for(x=0;x++<NF;)if($x==v){for(y=4;--y;) print _[(NR-y)];printf "\n"}}' file

To keep the forums high quality for all users, please take the time to format your posts correctly.

First of all, use Code Tags when you post any code or data samples so others can easily read your code. You can easily do this by highlighting your code and then clicking on the # in the editing menu. (You can also type code tags

```text
 and 
```

by hand.)

Second, avoid adding color or different fonts and font size to your posts. Selective use of color to highlight a single word or phrase can be useful at times, but using color, in general, makes the forums harder to read, especially bright colors like red.

Third, be careful when you cut-and-paste, edit any odd characters and make sure all links are working property.

Thank You.

The UNIX and Linux Forums