Select clustered residues of same type

GROMACS version: 2023.3
GROMACS modification: No

I am working with lipid membranes and would like to separate phospholipids which are part of the membrane from those which are free in solution. My initial thought for how to do this is to use gmx select to find headgroups which are not near other headgroups. However I cannot figure out the select invocation that will accomplish this. I have been trying variations of

gmx select -s md.gro -f md.gro -on membrane.ndx -select '"mPC" same residue as resname PC and within 0.4 of resname "PC"'

However this selects all PC residues because every atom is seeing its own bonded neighbors as within 0.4 (duh). Is there a way to exclude the atom’s own residue from the within selection?

So this does work:

gmx select -s md.tpr -f $1 -on P31.ndx -select 'atomname P31'
export GMX_MAXBACKUP=-1
printf '[ bad_P31 ]\n' > bad_P31.ndx
printf '' > nneigh.txt
for id in $(tail -n +2 P31.ndx | tr '\n' ' '); do
    gmx select -quiet -s md.tpr -f $1 -on tmp.ndx -select "(resname PC) and (within 0.8 of atomnr ${id}) and (not same residue as atomnr ${id})"
    nneigh=$(tail -n +2 tmp.ndx | tr -s ' ' | wc -w)
    if [ $nneigh -lt 1 ]; then
        printf "$id " >> bad_P31.ndx
    fi
    printf "$nneigh " >> nneigh.txt
done

However it’s quite slow. Does anybody have a better idea?