When matching patterns with / in them, having to escape the / quickly becomes unwieldy, ugly:


With sed, perl or Vim, I would use a different delimiter for the regex, say ::

sed '\:/usr/share/man/: do something'
perl -ne 'print if m:/usr/share/man/:'
:g:/usr/share/man/: do something " Vim

How can I avoid this awk? Something like:

awk ':/usr/share/man/: {do something}'

The best I can think of is to use a variable:

awk -v pat='/usr/share/man/' '$0 ~ pat {do something}'

But that is very verbose compared to the sed/perl/vim method.

Of course, there might be other ways to match paths like /usr/share/man/, but that's not the only place where / could appear in a pattern.

  • 2
    you could do '$0 ~ "/usr/share/man/" {do something}' instead of using variable... – Sundeep Apr 19 '17 at 3:31
  • 1
    @Sundeep I could, but the reason I brought it out is that this way I get to retain a layer of quoting (compare -v pat='"/' vs '$0 ~ "\"/"'). – muru Apr 19 '17 at 3:43
  • yup, that is true... and there is whole lot of escaping trouble while assigning something to awk variable which includes bash variables.. for ex: -v regex="^\\\s*$1\\\>" ... I don't think there is a way to use different regex delimiter than /regex/ so will have to use whatever fits case by case basis – Sundeep Apr 19 '17 at 3:50

Just change /testregexp/ with $0 ~ "testregexp"

Simple exemple:

$ echo "a/b/c" | awk ' ( $0 ~ "a/b/c" ) { print "we have a winner" ; }'
we have a winner

another exemple

regexp='some regexp "with /lots/ of double quotes" "everywhere"'
awk -v reg="${regexp}" ' ( $0 ~ reg ) { action here... }'
  • See comments on the question. – muru Apr 19 '17 at 16:05

Awk by itself doesn't have any easy, straightforward antidote for this. In the general case, switching to Perl (or down to sed for simple tasks) is the common workaround.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.