jimmy_y
1
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,
Thanks
skmdu
2
$grep -B 1 "word"
-B 1 is for 1 line before match.
jimmy_y
3
Thanks, but i tried, the output is:
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"
skmdu
5
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.
jimmy_y
6
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
skmdu
7
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..
jimmy_y
8
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 ----------
diff cmd.txt a.txt | grep "<" | cut -c3- > new.txt
sed -n '/word/!{h;}
/word/{H;x;p;}'