Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search pattern containing forward slash using AWK

Tags:

awk

In AWK, is there a way to match pattern containing forward slash / without actually escaping it?

awk '$1~/pattern/' file

The above command works fine as long as there isn't any / in the pattern.

I am looking for something similar to what's available in sed for using different separators in search and replace syntax.

like image 537
jkshah Avatar asked Nov 05 '13 13:11

jkshah


People also ask

How do you escape the forward slash in awk?

One use of an escape sequence is to include a double-quote character in a string constant. Because a plain double quote ends the string, you must use ' \" ' to represent an actual double-quote character as a part of the string. For example: $ awk 'BEGIN { print "He said \"hi!\

What is print$ 0 in awk?

When lines containing ' li ' are found, they are printed because ' print $0 ' means print the current line. (Just ' print ' by itself means the same thing, so we could have written that instead.) You will notice that slashes (' / ') surround the string ' li ' in the awk program.

How do I use awk patterns?

Any awk expression is valid as an awk pattern. The pattern matches if the expression's value is nonzero (if a number) or non-null (if a string). The expression is reevaluated each time the rule is tested against a new input record.

What is awk regex?

A regular expression enclosed in slashes (' / ') is an awk pattern that matches every input record whose text belongs to that set. The simplest regular expression is a sequence of letters, numbers, or both. Such a regexp matches any string that contains that sequence.


2 Answers

Yes, you can do

awk '$0~v' v="patt/ern"

Explanation

N.B.: extracted from comments, so upvote them too!

In awk dynamic regex and regex constant are not exactly same. The example in OP's question was regex constant you turned it into dynamic regex (see. Using Dynamic Regexps).

like image 155
Jotne Avatar answered Nov 09 '22 16:11

Jotne


This may be OK for you:

kent$ echo "///aaa"|awk '/[/]/'
///aaa
like image 28
Kent Avatar answered Nov 09 '22 16:11

Kent