5

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

/\/usr\/share\/man\//

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.

3
  • 2
    you could do '$0 ~ "/usr/share/man/" {do something}' instead of using variable...
    – Sundeep
    Apr 19, 2017 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, 2017 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, 2017 at 3:50

2 Answers 2

1

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... }'
1
  • See comments on the question.
    – muru
    Apr 19, 2017 at 16:05
0

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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .