wolfmason
wolfmason

Reputation: 409

Why is awk sub/gsub just erasing matches?

I'm using awk in a batch file on windows. For some reason sub/gsub is erasing matches, rather than replacing. I'm pulling my hair out over this...Here's a sample line:

awk "{ gsub(/ZSection/, "Section"); print}" temp1.txt > temp2.txt

Result: "ZSection" is just gone in temp2.txt. No "Section", anywhere.

I'm using sub/gsub in other scripts on my machine without issue, same syntax (I think? Unless I'm just going blind and/or insane).

What am I missing? Is it possible some other operation in the batch file is screwing with the functionality of sub/gsub? Help!

Upvotes: 3

Views: 819

Answers (3)

Birei
Birei

Reputation: 36262

Your problem seems to be the same quotes for the script and for your replacement string. Substitute the outer pair with single quotes:

awk '{ gsub(/ZSection/, "Section"); print}' temp1.txt > temp2.txt

Upvotes: 7

wolfmason
wolfmason

Reputation: 409

awk "{ gsub(/ZSection/, \"Section\"); print}" temp1.txt > temp2.txt

Found another overflow question regarding quotes with awk in windows 7 (thanks to other posters for mentioning quotes, though their solutions didn't work). The solution there suggested a syntax similar to \""Section\"". This worked, but it appears to be one more set of quotes than necessary for my script to work. It's all in the slashes...

Upvotes: 1

Kent
Kent

Reputation: 195079

this is your code, which doesn't work.

awk "{ gsub(/ZSection/, "Section"); print}" temp1.txt

This is the correct code:

awk '{ gsub(/ZSection/, "Section"); print}' temp1.txt

can you find the difference?

If we go a little deeper, your matched pattern was removed. because the variable Section was not set with any value. yes, here awk thinks the Section is a variable. If you want to prove it:

awk "{Section=555; gsub(/ZSection/, "Section"); print}" temp1.txt
awk "{Section=\"hello\"; gsub(/ZSection/, "Section"); print}" temp1.txt

check the output of above two lines, you will see.

the 2nd part of my answer just for explaining why the matches were removed. However we should quote the command correctly.

Upvotes: 9

Related Questions