问题描述
我想从管道分隔文件中提取存在某些模式的子字符串,因此我在下面的命令中使用了
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
在这里,"REWARD REQ.服务器头"是一种模式,可以在文件中进行搜索,并将其前4个部分打印在冒号分隔的行上.
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.
现在,我想发送bash变量作为模式.因此我使用了下面的命令,但是它不起作用.
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
如何在单个awk
命令中使用-v
和-F
?
How can I use -v
and -F
in a single awk
command?
推荐答案
此处的问题与-F
无关.
问题是当您想将pat
用作变量时使用/pat/
.如果您说/pat/
,则awk
会将其理解为文字"pat",因此它将尝试匹配包含字符串"pat"的行.
The problem is the usage of /pat/
when you want pat
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:
awk -v pat="$pattern" '$0 ~ pat'
总共,您的代码应为:
awk -v pat="$pattern" -F ":" '$0~pat{print $1, $2, $3, $4 }' file
# ^^^^^^
查看示例:
See an example:
提供此文件:
$ cat file
hello
this is a var
hello bye
让我们寻找包含"hello"的行:
Let's look for lines containing "hello":
$ awk '/hello/' file
hello
hello bye
现在让我们尝试按照您的操作方式查找变量中包含的"pat":
Let's now try looking for "pat", contained in a variable, the way you were doing it:
$ awk -v pat="hello" '/pat/' file
$ # NO MATCHES!
现在让我们使用$0 ~ pat
表达式:
Let's now use the $0 ~ pat
expression:
$ awk -v pat="hello" '$0~pat' file
hello # WE MATCH!
hello bye
当然,您可以使用此类表达式来匹配一个字段并说出awk -v pat="$pattern" '$2 ~ pat' file
,依此类推.
Of course, you can use such expressions to match just one field and say awk -v pat="$pattern" '$2 ~ pat' file
and so on.
BEGIN { digits_regexp = "[[:digit:]]+" }
$0 ~ digits_regexp { print }
这会将digits_regexp设置为描述一个或多个数字的正则表达式, 并测试输入记录是否与此正则表达式匹配.
This sets digits_regexp to a regexp that describes one or more digits, and tests whether the input record matches this regexp.
这篇关于如何匹配awk变量中给定的模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!