Skip site navigation (1)Skip section navigation (2)
Date:      Fri, 4 Sep 1998 09:53:58 -0500
From:      Dan Nelson <dnelson@emsphone.com>
To:        Roman Katsnelson <romank@graphnet.com>, "q's" <freebsd-questions@FreeBSD.ORG>
Subject:   Re: grep question
Message-ID:  <19980904095358.A7658@emsphone.com>
In-Reply-To: <35EFEEA4.65B3315F@graphnet.com>; from "Roman Katsnelson" on Fri Sep  4 09:44:04 GMT 1998
References:  <35EFEEA4.65B3315F@graphnet.com>

next in thread | previous in thread | raw e-mail | index | archive | help
In the last episode (Sep 04), Roman Katsnelson said:
> I have one text file with many records. Each record is 16 lines long.
> The record's identifier is always the third line because it's unique.
> The records look like this:
> 
> <blank line>
> ##################################
> # --->uniquerecordname
> ##################################
> recorddata 12 more lines worth.
> 
> I am writing a script which will automate deleting the records. Here's
> what I've done:
> 
> grep -e "uniquerecordname" -A 13 -B 2 #this yields the record correctly.
> 
> however,
> 
> grep -e "uniquerecordname" -A 13 -B 2 -v #does NOT yield the inverse,
> which should be the rest of the file without the record. 

Well, it does, sort of. :)   The -v is applied first.  Then, any
matches are expanded to show the -AB context.  Since you don't have a
run of 16 consecutive lines with "uniquerecordname" in them, the
leading/trailing context on every non-matching line overlaps your one
match, and grep ends up printing every line.

> i've tried outputting the grep result in the first example to a new
> file, and then doing a diff on the two -- that works, but it puts a >
> in the beginning of each line, which is unacceptable.

You could pipe THAT output through `` sed -e "s/^> //" '', which would
remove the "> ".

> Is there any other way to do this that I haven't thought of yet?

How about this:

--- deleterecord ---
#!/bin/sh

file="file.txt"
recid=$1
# get the starting line number for the record we're interested in
line=$(grep -n "^# --->$recid" $file) # grep -n prepends line with line num
linenum=${line%%:*}  # remove everything after the first colon

if [ -z "$linenum" ] ; then
	echo Record $recid not found
	exit 1
fi

# calculate the start and end line numbers
start=$(( $linenum - 2 ))
end=$(( $linenum + 13 ))

# delete the offending record
sed -e "${start}-${end}d" < $file > $file.tmp
mv $file.tmp $file
---

	-Dan Nelson
	dnelson@emsphone.com

To Unsubscribe: send mail to majordomo@FreeBSD.org
with "unsubscribe freebsd-questions" in the body of the message



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?19980904095358.A7658>