1

I have very long file.txt which, among other hundreds of lines, contains lot of lines like these ones:

CD  H1
CD  H123 
CD  C2 
CD  D1
CD  H2FOO
CD  HXY

I want file which doesn't contain lines with words starting with H, except lines with word H1 ie, I want following lines:

CD  H1 
CD  C2 
CD  D1

Thanks.

Edit, part of full example:

ATOM    127  HN1 POPE    2      -1.381  -4.751  17.480  1.00  0.00      MEMB
ATOM    128  HN2 POPE    2      -2.752  -4.808  18.466  1.00  0.00      MEMB
ATOM    129  HN3 POPE    2      -2.694  -3.943  16.950  1.00  0.00      MEMB
ATOM    130  C12 POPE    2      -1.684  -3.060  18.702  1.00  0.00      MEMB
ATOM    131 H12A POPE    2      -0.774  -2.666  18.200  1.00  0.00      MEMB
ATOM    132 H12B POPE    2      -1.447  -3.420  19.726  1.00  0.00      MEMB
ATOM    133  C11 POPE    2      -2.802  -1.944  18.718  1.00  0.00      MEMB
ATOM    134 H11A POPE    2      -3.229  -1.764  17.709  1.00  0.00      MEMB
ATOM    135 H11B POPE    2      -2.235  -1.057  19.074  1.00  0.00      MEMB
ATOM    136  P   POPE    2      -5.353  -2.326  19.349  1.00  0.00      MEMB
ATOM    137  O13 POPE    2      -5.649  -1.230  18.368  1.00  0.00      MEMB

I want following lines:

ATOM    127  HN1 POPE    2      -1.381  -4.751  17.480  1.00  0.00      MEMB
ATOM    129  HN3 POPE    2      -2.694  -3.943  16.950  1.00  0.00      MEMB
ATOM    130  C12 POPE    2      -1.684  -3.060  18.702  1.00  0.00      MEMB
ATOM    133  C11 POPE    2      -2.802  -1.944  18.718  1.00  0.00      MEMB
ATOM    136  P   POPE    2      -5.353  -2.326  19.349  1.00  0.00      MEMB
ATOM    137  O13 POPE    2      -5.649  -1.230  18.368  1.00  0.00      MEMB

So to re-formulate question based on this example: I need lines which doesn't contain words starting with H except lines with words HN1 and HN3

3 Answers 3

2

Since your data records are structured (as whitespace delimited columns), you may find it easier to use awk so that you can target the specific column.

KISS approach using separate tests

awk '$3 ~ /^[^H]/ || $3 == "H1"' file

or (using regex only)

awk '$3 ~ /^([^H]|H1$)/' file
0

Hope this helps:

cat file.txt | grep -v H[1-9] > tofile.txt
0

Use negative matching (grep -v) with a negative look-behind that rejects HN1/HN3:

grep -Pv '\sH(?!N[13]\s)' <data

grep -P (perl regex, required for the look-behind support) is non-POSIX and only in Gnu grep (the grep in most Linux distros).

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .