user2023370
user2023370

Reputation: 11046

Awk find and replace for exact match only

If I'd like to replace a character field, say {, with awk I can use:

awk '{ gsub(/{/, "<"); print }' file

...but this will also replace a field such as "{" (which I don't want). Is there an awk function which will find only an exact match (and replace) of an entire field; for all fields.

For example, the following:

$ echo "foo bar zod \"{\" {" | awk '{ gsub(/{/, "<"); print }'

will output:

foo bar zod "<" <

but I'd like it to output:

foo bar zod "{" <

I could also explicitly iterate over the fields and use == to check for an exact match, but I wonder if there's an alternative.

Upvotes: 0

Views: 1665

Answers (1)

Kent
Kent

Reputation: 195209

I would do what you said, loop through all field, either checking with == or /^{$/.

However if we play some trick, it could be done without loop: (gnu awk)

awk '$0=gensub(/(\s|^){(\s|$)/, "\\1<\\2","g")'                                                                                  

check this example:

kent$ echo '{ foo "{" and this: { bar {'|awk '$0=gensub(/(\s|^){(\s|$)/, "\\1<\\2","g")'
< foo "{" and this: < bar <

In the example above, 3 of 4 { were substituted.

Upvotes: 3

Related Questions