10 月的第一周,Arnold Robbins 在 GNU 公告、bug-gawk 和 comp.lang.awk 中宣布 gawk 4.2.0 测试版现已发布邮件列表。可用于 http://www.skeeve.com/gawk/gawk-4.1.65.tar.gz 1,他提到这是一个主要版本,具有许多重要的新功能。
因此,我浏览了新闻文件来深入研究这些功能,并在此时停下来进行一些测试:
Changes from 4.1.4 to 4.2.0
...
- Revisions in the POSIX standard remove the special case for POSIX mode when FS = " " where newline was not a field separator. The code and doc have been updated.
如果我理解正确的话,他谈论的是GNU Awk User's Guide → 4.5.2 Using Regular Expressions to Separate Fields :
There is an important difference between the two cases of ‘FS = " "’ (a single space) and ‘FS = "[ \t\n]+"’ (a regular expression matching one or more spaces, TABs, or newlines). For both values of FS, fields are separated by runs (multiple adjacent occurrences) of spaces, TABs, and/or newlines. However, when the value of FS is " ", awk first strips leading and trailing whitespace from the record and then decides where the fields are.
也就是使用FS = ""
和FS = "[\t\n]+"
的区别。
我运行了新版本并使用 --posix
进行了测试模式:
$ ./gawk --posix -F" " '{print "NR:", NR; for(i=1;i<=NF;i++) print i, $i}' <<< "hello how are
you"
NR: 1
1 hello
2 how
3 are
NR: 2
1 you
与我之前的 awk (4.1.3) 相比,看不出有什么区别:
$ gawk --posix -F" " '{print "NR:", NR; for(i=1;i<=NF;i++) print i, $i}' <<< "hello how are
you"
NR: 1
1 hello
2 how
3 are
NR: 2
1 you
总而言之,我的问题是:GNU Awk 4.2 的 --posix
模式下 FS = ""
的行为有何不同?到底改变了什么?
1 是的,我也认为应该是 4.2.tar.gz
,但是 http://www.skeeve.com/gawk/gawk-4.2.tar.gz不存在
最佳答案
这是 4.2 的测试版,因此它是根据 4.1 构建/命名的。当它正式发布时,它将是 4.2.tar.gz。
我没有方便的 4.2 beta 来测试以下理论,但我认为关于默认 FS=""
的公告意味着:
以前在 POSIX 中,当您设置 FS=""
时,这意味着字段由所有空格字符分隔除换行符。另一方面,gawk 默认将换行符作为分隔符之一,并且您必须添加 --posix 才能获得 POSIX 行为。看:
$ gawk --version
GNU Awk 4.1.4, API: 1.1 (GNU MPFR 3.1.5, GNU MP 6.1.2)
$ printf 'a b\nc' | awk -v RS='^$' 'NR==1{for (i=1; i<=NF;i++) print NR, NF, i, "<" $i ">"}'
1 3 1 <a>
1 3 2 <b>
1 3 3 <c>
$ printf 'a b\nc' | awk --posix -v RS='^$' 'NR==1{for (i=1; i<=NF;i++) print NR, NF, i, "<" $i ">"}'
1 2 1 <a>
1 2 2 <b
c>
显然,现在 POSIX 标准已更新为在 FS=""
时将 \n
包含在分隔符字符集中,因此 gawk 不再需要在该方面表现不同尊重 posix 与非 posix 模式,相反,所有 POSIX awks 都需要更新为默认情况下 gawk 的行为。
您问题中的示例没有测试这一点,因为它使用 \n
作为 RS(默认),因此无法测试当 \n
位于范围内时会发生什么一个记录。设置RS="^$"
后重试。
关于awk - GNU Awk 4.2 中 FS = ""的行为是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46609071/