Monday, October 10, 2011

Use of character range in awk, thanks to UNIX and Linux Forums

I knew most of this, but there is definitely some subtlety in the quoting of the "[" "]" in the response... :-)

Happy hunting,

Use of character range in awk - The UNIX and Linux Forums:

Registered User

Join Date: Oct 2011
Posts: 2
Thanks: 1
Thanked 0 Times in 0 Posts
Use of character range in awk

Hi all,
I am having a bit of a hard time using awk. I must do something wrong, but I don't know what... Any help would be greatly appreciated!

I read a file, as follows :
... ATOM     21  C   THR A   4      23.721 -26.194   1.909  1.00 32.07           C     ATOM     22  O   THR A   4      24.874 -26.014   1.536  1.00 32.36           O     ATOM     23  CB  THR A   4      22.548 -26.219  -0.334  1.00 31.56           C     ATOM     26  N   CYS A   5      23.261 -25.726   3.072  1.00 32.18           N     ATOM     27  CA  CYS A   5      24.119 -24.983   4.010  1.00 32.76           C     ...

It has thousands of lines like this. I wish to sort some data out, but only when column 5 (here an "A") is within a range of letters accessible via the variabledata. data is a user input and can be any letters in the range A-Z, in any combinaison (i.e. "F", "ABCFIZ", "A-GX", "KJHGF", ...). So I do this :
awk '{if ($5 == "'[$data]'" ) {do_something}}' $in >> $out

That it is not working. If I put a single letter (e.g.
$5 == "A"), it works just fine, but as long as I want a variable, it doesn't output anything. I tried A LOT of combinaison around the metacharacters [] , like : "'[$data]'", "'['$data']'", "'\[$data\]'", "'["$data"]'", etc and nothing works - and often yielded errors. I'm out of ideas, if anyone has a suggestion...

I may add, for precision sake, that the quoted awk code is within a much longer script, called from and programmed into tcsh.

vgersh99's Avatar

Join Date: Feb 2005
Location: Boston, MA
Posts: 6,527
Thanks: 50
Thanked 245 Times in 238 Posts

nawk -v r='A-C' '$5 ~ "[" r "]"' myFile

'via Blog this'

No comments:

Post a Comment