[TriLUG] regex: match lines NOT containing X

Mitchell Amiano mamiano at nc.rr.com
Wed Feb 22 11:47:10 EST 2012


The grep -v solution is what I usually use in the shell.
It is also possible to use sed to stream edit.  
Assume content is in file called "text":

sed -e '/heads/ d'  text

Shell parameter substitution can also do the job. 
It is slower for longer texts, but you can often avoid forking a process:

lines=()
 while read line; do
  if [[ "${line}" == "${line%%heads*}" ]]; then
    lines[${#lines[*]}]="$line"
  fi
done < text

for (( x=0; $x < ${#lines[*]}; x=$x+1 )) ; do 
  echo ${lines[$x]}
done
are two keyboards better than one?


On Feb 22, 2012, at 9:56 AM, Kevin Hunter wrote:

> Hullo List,
> 
> An actual technical question here: Is there a way to match an entire line such that the entire line does *not* contain a sequence of characters?
> 
> Example input containing three lines:
> -----
> If two heads are better than one,
> are two keyboards better than one?
> Would you say the same if it were two hydra heads?
> -----
> 
> My criteria is very specific: I want lines that do *not* contain 'heads'.  My first thought was to use an assertion:
> 
> /^.*two.*(?!heads).*$/
> 
> However, this naive implementation matches both lines 2 and 3.  I've needed this construct more than a few times, so I'm almost sure it exists; I just don't know the right Google terms, apparently.  On the other hand, I could accept that this may not be possible in a single step regex.
> 
> Any ideas?
> 
> Thanks,
> 
> Kevin
> -- 
> This message was sent to: Mitch Amiano <mamiano at nc.rr.com>
> To unsubscribe, send a blank message to trilug-leave at trilug.org from that address.
> TriLUG mailing list : http://www.trilug.org/mailman/listinfo/trilug
> Unsubscribe or edit options on the web	: http://www.trilug.org/mailman/options/trilug/mamiano%40nc.rr.com
> TriLUG FAQ          : http://www.trilug.org/wiki/Frequently_Asked_Questions

Mitchell Amiano
(919) 410-8008
mamiano at nc.rr.com







More information about the TriLUG mailing list