merlin2011
merlin2011

Reputation: 75589

Is it possible to use alternate delimiters for awk's gsub function?

Consider the following substitution in awk.

echo 'hello/bar/goo'  | awk '{gsub(/\//,"foo"); print}'

The output is the following.

hellofoobarfoogoo

Observe that we had to escape the / in the first argument to gsub because / is the default delimiter of the regex in awk's gsub function.

Considering the fact that we could solve the same problem in sed with a change of delimiter as below, I wonder whether the same is possible with gsub.

echo 'hello/bar/goo'  | sed 's!/!foo!g'

I have tried both of the following, but they result in syntax errors.

echo 'hello/bar/goo'  | awk '{gsub(!/!,"foo"); print}'                                                                                                         
awk: cmd. line:1: {gsub(!/!,"foo"); print}
awk: cmd. line:1:         ^ unterminated regexp
awk: cmd. line:2: {gsub(!/!,"foo"); print}
awk: cmd. line:2:                         ^ unexpected newline or end of string

echo 'hello/bar/goo'  | awk '{gsub(|/|,"foo"); print}'
awk: cmd. line:1: {gsub(|/|,"foo"); print}
awk: cmd. line:1:       ^ syntax error
awk: cmd. line:1: {gsub(|/|,"foo"); print}
awk: cmd. line:1:         ^ unterminated regexp

Is there some option I can set in awk to allow alternate delimiters for gsub?

If so, what is the set of allowable alternate delimiters?

Upvotes: 0

Views: 661

Answers (2)

Avinash Raj
Avinash Raj

Reputation: 174826

You could use double quotes as delimiter.

echo 'hello/bar/goo'  | awk '{gsub("/","foo"); print}'

But careful when dealing with the backslash, since you need to use four backslashes in-order to match a single backslash.

$ echo 'hello/bar\goo' | awk '{gsub("\\\\","foo"); print}'
hello/barfoogoo

Upvotes: 1

Jotne
Jotne

Reputation: 41460

Only delimiter for regex in awk is /, but you can as Avinash showed, search for a string "something". No other option possible.

Upvotes: 0

Related Questions