I want to extract a substring where certain pattern exist from pipe separated file, thus I used below command,
awk -F ":" '/REWARD REQ. SERVER HEADERS/{print $1, $2, $3, $4}' sample_profile.txt
Here, 'REWARD REQ. SERVER HEADERS' is a pattern which is to be searched in the file, and print its first 4 parts on a colon separated line.
Now, I want to send bash variable to act as a pattern. thus I used below command, but it's not working.
awk -v pat="$pattern" -F ":" '/pat/{print $1, $2 , $3, $4 } sample_profile.txt
How can I use -v
and -F
in a single awk
command?
The problem here does not have to do with
-F
.The problem is the usage of
/pat/
when you wantpat
to be a variable. If you say/pat/
,awk
understands it as a literal "pat", so it will try to match those lines containing the string "pat".If you want to provide the pattern through a variable, you need to use
~
as this:All together, your code should be:
See an example:
Given this file:
Let's look for lines containing "hello":
Let's now try looking for "pat", contained in a variable, the way you were doing it:
Let's now use the
$0 ~ pat
expression:Of course, you can use such expressions to match just one field and say
awk -v pat="$pattern" '$2 ~ pat' file
and so on.From GNU Awk User's Guide → 3.1 How to Use Regular Expressions:
And GNU Awk User's Guide → 3.6 Using Dynamic Regexps:
This is kind of a hack but it makes things a little simpler for me.
making it a string first lets you manipulate it past the boundaries of awk
You can't use the variable inside the regex
//
notation (there's no way to distinguish it from searching forpat
); you have to specify that the variable is a regex with the~
(matching) operator.