|
Home > Archive > Unix questions > October 2004 > sed question
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
|
|
| usatim 2004-10-15, 9:28 pm |
| how can I find a string in a file, print that line and the next two lines?
| |
| Chris F.A. Johnson 2004-10-15, 9:28 pm |
| On 2004-10-13, usatim wrote:
> how can I find a string in a file, print that line and the next two lines?
Why sed?
If you have GNU grep:
grep -A2 "$string" file
With awk:
awk "/$string/ {print; getline; print; getline; print; exit}"
With the shell:
while IFS= read -r line
do
case $line in
*"$string"*) printf "%s\n" "$line"
IFS= read -r line
printf "%s\n" "$line"
IFS= read -r line
printf "%s\n" "$line"
exit
;;
esac
done < file
And if you really want to use sed:
sed -n "/$string/{p;n;p;n;p;q;}" file
--
Chris F.A. Johnson http://cfaj.freeshell.org/shell
========================================
===========================
My code (if any) in this post is copyright 2004, Chris F.A. Johnson
and may be copied under the terms of the GNU General Public License
| |
| usatim 2004-10-15, 9:28 pm |
| "Chris F.A. Johnson" <cfajohnson@gmail.com> wrote in message news:<2t5lobF1smmp7U1@uni-berlin.de>...
> On 2004-10-13, usatim wrote:
>
> Why sed?
>
> If you have GNU grep:
>
> grep -A2 "$string" file
>
>
> With awk:
>
> awk "/$string/ {print; getline; print; getline; print; exit}"
>
>
> With the shell:
>
> while IFS= read -r line
> do
> case $line in
> *"$string"*) printf "%s\n" "$line"
> IFS= read -r line
> printf "%s\n" "$line"
> IFS= read -r line
> printf "%s\n" "$line"
> exit
> ;;
> esac
> done < file
>
>
> And if you really want to use sed:
>
> sed -n "/$string/{p;n;p;n;p;q;}" file
Thanks for the response. I was close but I did not have the brackets
and I did not have the last ;.
I know how to find a string and delete it with sed but I have no clue
about how to find string1 and if the next line is string2, delete both
lines, throughout a file. This should be the last time I bother
everyone.
Is there a good sed book I can get. I am not happy with the one I have
(O'Reilly, sed & awk).
| |
| rakesh sharma 2004-10-15, 9:28 pm |
| tillman.h.craft@usa-spaceops.com (usatim) wrote in message news:
>
> I know how to find a string and delete it with sed but I have no clue
> about how to find string1 and if the next line is string2, delete both
> lines, throughout a file. This should be the last time I bother
> everyone.
>
sed -e '
/string1/!b
$!N
/\nstring2/d
' yourfile
>
> Is there a good sed book I can get. I am not happy with the one I have
> (O'Reilly, sed & awk).
>
That's the only book or look for the sed one-liners web site where
there are good tutorials on 'sed'.
|
|
|
|
|