awk gsub regex expression, match word not in double quotes

Viewed 135

I wrote a regular expression to try and replace a every occurrence of a word not in double quotes using gsub with awk. However even though the expression works with online calculators the expression doesn't replace anything at all in my script.

input =

studentNum=="00000"{print name, "is the prof"}

expression:

gsub( "studentNum(?=[^"]*(?:"[^"]*"[^"]*)*$)", "XXX", input)

expected output:

XXX=="00000"{print name, "is the prof"}

2 Answers

With match function: awk doesn't support look-ahead mechanism, with your shown samples please try following.

awk '
match($0,/^studentNum=="[0-9]+"{.*}$/){
  val=substr($0,RSTART,RLENGTH)
  sub(/^[^"]*/,"XXX==",val)
  print val
}
'  Input_file

Without match function:

awk '
/^studentNum=="[0-9]+"{.*}$/{
  sub(/^[^"]*/,"XXX==")
}
1
'  Input_file

Explanation: Simple explanation would be: Using match function of awk here to match studentNum==" digits "{ till end of line here. Then substituting everything from starting till 1st occurrence of " with XXX== in matched value, then printing the matched value.

Bonus solution(with match): In case you have lines which doesn't match condition and you want to print both matching condition and non-matching both lines then try following:

awk '
match($0,/^studentNum=="[0-9]+"{.*}$/){
  val=substr($0,RSTART,RLENGTH)
  sub(/^[^"]*/,"XXX==",val)
  $0=val
}
1
'  Input_file

Online regexp validators only prove that your regexp works with that particular online regexp validator, it doesn't prove it'll work with any given command-line tool. In particular your regexp is a PCRE while sed by default supports BREs and awk supports EREs. There are no mandatory POSIX tools that support PCREs.

Is this what you're trying to do?

$ sed 's/studentNum\(=="[^"]*"\)/XXX\1/' file
XXX=="00000"{print name, "is the prof"}

$ awk '{print gensub(/studentNum(=="[^"]*")/,"XXX\\1",1)}' file
XXX=="00000"{print name, "is the prof"}

The sed script will work in any sed, the awk script requires an awk that has gensub(), e.g. GNU awk.

Related