awk 中的匹配忽略空格
1 #!/bin/bash
2 KEY_FILE="keys"
3 TABLE_FILE="table" #pipe delimited data
4
5 i=0;
6 while read key #print out rows in table file with key in keys file
7 do
8 let i=i+1
9 # key is first column in table
10 # print status to stderr
11 (echo "$KEY_FILE : line $i" >&2)
12 awk -F '|' "\$1 == $key {print \$0}" $TABLE_FILE
13 done < $KEY_FILE
14
从第 12 行开始,如果存在空格差异,awk 是否会将第一列与键进行匹配?
1 #!/bin/bash
2 KEY_FILE="keys"
3 TABLE_FILE="table" #pipe delimited data
4
5 i=0;
6 while read key #print out rows in table file with key in keys file
7 do
8 let i=i+1
9 # key is first column in table
10 # print status to stderr
11 (echo "$KEY_FILE : line $i" >&2)
12 awk -F '|' "\$1 == $key {print \$0}" $TABLE_FILE
13 done < $KEY_FILE
14
From line 12, will awk match the first column against the key if there is a white space discrepancy?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,因为您设置了字段分隔符。空白字符现在很重要。
您可以将字段分隔符设置为正则表达式来消除空格。另外,将 shell 变量的值传递给 awk 变量以避免引用 hell。
请注意,
{print $0}
是默认操作,因此可以省略。另外,awk 可以处理两个文件,因此您不需要 bash 循环:
表达式
NR == FNR
表示 awk 正在查看文件列表中的第一个文件(NR 是“总记录数”,FNR 是当前文件的记录数:它们仅与第一个文件相同)。该程序将键保存在key
数组中,并打印表文件中包含该数组中的键的记录。No, because you set your field separator. Whitespace characters are now significant.
You can set your field separator to be a regular expression to slurp up whitespace. Also, pass the value of the shell variable into an awk variable to avoid quoting hell.
Note that
{print $0}
is the default action, so that can be omitted.Also, awk can handle two files, so you don't need the bash loop:
The expression
NR == FNR
means that awk is looking at the first file in the list of files (NR is the "total record number" and FNR is the record number of the current file: they will only be the same for the first file). This program saves the keys in thekey
array, and the prints the records in the table file that have a key in that array.