I have to grep on a few words in a file and then display the line containing those words and the line above it.
For ex -
File1.txt contains...
abc xyz abc
This is a test
Test successful
abc xyz abc
Just a test
Test successful
I find the words 'Test successful' in the file and then I have to display the line containing these words and the line above it.
So my output should be...
This is a test
Test successful
Just a test
Test successful
I am just not sure how to display the line above the 'Test successful' in my result.
cabrao
2
grep -B1 "Test successful" yourfile
var=`grep -n "Test successful" <filename> | cut -f1 -d ":"`
for i in $var
do
head -$i <filename> | tail -2
done
use this awk utility
awk 'c-->0;$0~s{if(b)for(c=b+1;c>1;c--)print r[(NR-c+1)%b];print;c=a}b{r[NR%b]=$0}' b=1 a=0 s="Test successful" filename
where a=no of lines below the pattern
b=no of lines above the pattern
s=pattern
aster007,
that worked very well...
Can you also let me know how can I get the same result from all files in the directory (using '*') rather than putting <filename>?
for file in *
do
var=`grep -n "Test successful" $file | cut -f1 -d ":"`
for i in $var
do
head -$i $file | tail -2
done
done
That worked awsome!
Thank you -- Peterro and aster007.