regex - 将变量传递给awk并在正则表达式中使用它

标签 regex variables awk

我正在学习awk,在将变量传递到脚本并将其用作正则表达式搜索模式的一部分时遇到了麻烦。

该示例是人为设计的,但显示了我的探针。

我的数据如下:

Eddy        Smith       0600000000  1981-07-16    Los Angeles
Frank       Smith       0611111111  1947-04-29    Chicago           
Victoria    McSmith     0687654321  1982-12-16    Los Angeles
Barbara     Smithy      0633244321  1984-06-24    Boston            
Jane        McSmithy    0612345678  1947-01-15    Chicago               
Grace       Jones       0622222222  1985-10-07    Los Angeles
Bernard     Jones       0647658763  1988-01-01    New York          
George      Jonesy      0623428948  1983-01-01    New York          
Indiana     McJones     0698732298  1952-01-01    Miami             
Philip      McJonesy    0644238523  1954-01-01    Miami

我想要一个可以传递变量的awk脚本,然后让awk脚本对该变量进行正则表达式。
我现在将这个脚本命名为“003_search_persons.awk”。
#this awk script looks for a certain name, returns firstName, lastName and City

#print column headers
BEGIN {
    printf "firstName lastName City\n";
}

#look for the name, print firstName, lastName and City
$2 ~ name {
    printf $1 " " $2 " " $5 " " $6;
    printf "\n";
}

我这样称呼脚本:
awk -f 003_search_persons.awk name=Smith 003_persons.txt

它返回以下内容,这很好。
firstName lastName City
Eddy Smith Los Angeles
Frank Smith Chicago
Victoria McSmith Los Angeles
Barbara Smithy Boston
Jane McSmithy Chicago

但是现在我要查找某个前缀“Mc”。我当然可以对此进行硬编码,但是我想要一个灵活的awk脚本。我在003_search_persons_prefix.awk中编写了以下内容。
#this awk script looks for a certain prefix to a name, returns firstName, lastName and City

#print column headers
BEGIN {
    printf "firstName lastName City\n";
}

#look for the prefix, print firstName, lastName and City
/^prefix/{
    printf $1 " " $2 " " $5 " " $6;
    printf "\n";
}

我这样称呼脚本:
awk -f 003_search_persons_prefix.awk prefix=Mc 003_persons.txt

但是现在找不到任何记录。

问题是搜索模式“/ ^ prefix /”。我知道我可以像第一个脚本中那样用非正则表达式替换该搜索模式,但是假设我想用正则表达式进行搜索,因为我需要前缀确实位于lastName字段的开头,因为它应该是前缀和所有;-)

我该怎么做呢?

最佳答案

你可以试试这个

BEGIN{
 printf "firstName lastName City\n";
 split(ARGV[1], n,"=")
 prefix=n[2]
 pat="^"prefix
}
$0 ~ pat{
    print "found: "$0
}

输出
$ awk -f  test.awk name=Jane file
firstName lastName City
found: Jane        McSmithy    0612345678  1947-01-15    Chicago

进一步了解awk documentation。 (并从头到尾阅读它!)

关于regex - 将变量传递给awk并在正则表达式中使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2227583/

相关文章:

mysql - 1-50 不带小数点的正则表达式

java - 正则表达式帮助

javascript - 使用输入变量和表单名称来引用输入元素

bash - AWK 按变量值打印字段

unix - 除空行外,每一行都用单引号括起来

Python 搜索字符串中的值

PHP - 包含文件而不继承变量?

linux - 如何打印特定行和列中的数字

linux - AWK,如何计算uniq http代码

javascript - 仅当 JavaScript 中出现多个空格时才分割字符串