我正在学习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字段的开头,因为它应该是,作为前缀和所有; - )
我该怎么做?
答案 0 :(得分:16)
你可以试试这个
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了解更多信息。 (并从头到尾阅读!)
答案 1 :(得分:5)
将您的脚本更改为:
BEGIN {
print "firstName", "lastName", "City"
ORS = "\n\n"
}
$0 ~ "^" prefix {
print $1, $2, $5, $6
}
并将其命名为
awk -v prefix="Mc" -f 003_search_persons.awk 003_persons.txt
答案 2 :(得分:1)
您应该可以不使用原始脚本 - $2 ~ name
已经在进行正则表达式搜索,因此如果您使用name=^Mc
调用脚本,则会返回以“Mc”开头的名称。实际上这不是一个很好的例子,因为Mc只出现在名字的开头 - 如果你使用name=^Smith
那么它会找到史密斯而不是麦克史密斯。
答案 3 :(得分:0)
特别需要awk吗?我确信它很可能在awk中,但我不知道,如果你只是需要完成工作,那么你可以试试。不确定那个分隔符究竟是什么。
cut -d " " -f1-2,5 file | egrep '^regex'