grep two lines in a file

Hi Everyone,
I have 1.txt

1
6-6
3-3
word
y
f
6-6
word
5-5
4
5-5
word

The output should be:

3-3
word
6-6
word
5-5
word

if i use grep, i can grep word, but if i want to get the line with word, and its previous line, how should i do, awk, sed, perl, :confused:

Thanks

$grep -B 1 "word"

-B 1 is for 1 line before match.

Thanks, but i tried, the output is: :confused:

3-3
word
--
6-6
word
--
5-5
word

if i do:

grep -B 1 "word" 1.txt | grep -v "\-\-"

then i can get the correct output. is there any way other than doing grep -v --. thanks

bash shell

while read -r line
do
 case "$line" in
    word*) printf "%s\n%s\n" $prev $line;;
 esac
 prev=$line
done < "file"

3-3 ## 1 line previous
word ## Matched line
-- ## delimiter
6-6
word
--
5-5
word
-- delimiter given by the grep command.

$ grep -B 1 "word" a | grep -v "\-\-"

Try this, it will give you the output as you expected.

if grep -B 1 "word" 1.txt, i cannot do grep -v -B 1 " word" 1.txt, how should i use -v with -B? thanks

grep command writes the delimiter to the file STDOUT. but grep command with its options are applicable for STDIN/Givenfilename.

So for your requirement, my guess is, you can not use -v "\-\-" and -B "word" in a single command..

Thanks

If i have two txt files:
1.txt

1
6-6
3-3
word
y
f
6-6
word
5-5
4
5-5
word
3-3
word
6-6
word
5-5
word

the output is:

1
6-6
y
f
5-5
4

please advice. thanks

---------- Post updated at 04:42 AM ---------- Previous update was at 03:56 AM ----------

:smiley:

diff cmd.txt a.txt | grep "<" | cut -c3- > new.txt
sed -n '/word/!{h;} 
/word/{H;x;p;}'