在awk中,可以使用正则表达式来过滤中间字符串。以下是一个示例代码:
#!/bin/awk -f
# 使用正则表达式过滤中间字符串
BEGIN {
regex = "hello"
}
{
# 将匹配到的字符串保存到数组中
while (match($0, regex)) {
matched_string = substr($0, RSTART, RLENGTH)
matched_strings[NR] = matched_string
$0 = substr($0, RSTART + RLENGTH)
}
}
# 打印匹配到的字符串
END {
for (i = 1; i <= NR; i++) {
print matched_strings[i]
}
}
假设上述代码保存为filter.awk文件,并给予执行权限。可以通过以下方式运行此脚本:
$ echo "hello world, hello awk" | awk -f filter.awk
输出结果为:
hello
hello
该示例中,使用了match()函数来查找匹配到的字符串,并使用substr()函数获取匹配到的字符串。匹配到的字符串保存在matched_strings数组中,最后通过循环打印出来。