user3614293
user3614293

Reputation: 425

.awk escape character inside regex

I don't quite understand how escape the character works in .awk scripts.

I have this line in the file I want to read:

 #Name Surname City Company State Probability Units Price Amount

If I just write:

awk < test.txt '/\#/ {print $1}'

in the command line, then everything is fine and the output is #Name.

However, if I try to do the same inside an .awk file the following way:

/\#/ {print $1};

I get no output for this. Also, gEdit won't recognize "\" as an escape character inside .awk for some reason.

Why is this happening and is there a workaround?

Upvotes: 2

Views: 658

Answers (2)

hwnd
hwnd

Reputation: 70732

This works for me, also you don't need to escape # because it is not a character of special meaning.

(my.awk) contents:

/#/ {print $1};

Then execute it by using the awk interpreter:

hwnd@lsh1001:~$ awk -f my.awk test.txt
#Name

Upvotes: 2

Ed Morton
Ed Morton

Reputation: 203985

# is not an RE meta-character so it doesn't need to be escaped in the context of an RE to have it taken literally.

I've no idea what gEdit is (nor do I want to so no need to explain!) so I can't help you with your question about that - maybe post another question with a gEdit tag so people who know that tool will look at it?

Running this on the command line:

awk '/\#/ {print $1}' test.txt

WILL produce the same output as:

awk -f tst.awk test.txt

assuming tst.awk contains:

/\#/ {print $1}

Again you do not need to escape the # but that's beside the point. If that's not what you are experiencing then the most likely reason is that the editor you used to create tst.awk corrupted the file somehow, maybe by adding control-Ms to the end of lines.

Finally - awk statements are terminated by newlines by default, no need to add spurious semi-colons at the end of lines and chances are you will put one somewhere you REALLY don't want it some day if you dont understand that.

Upvotes: 2

Related Questions