标签:special space inf 没有 ofo lines expr ret software
今天用 awk 格式化字符串的时候,发现了一个奇怪现象,查看了 awk 手册后,特以此文记录。后文所有 awk 语名中出现的 file.txt
内容均如下:
# cat -A file.txt
1^Iroot:x:0:0:root:/root:/bin/bash$
2^Ibin:x:1:1:bin:/bin:/sbin/nologin$
3^Idaemon:x:2:2:daemon:/sbin:/sbin/nologin$
通过 awk -F 的 "[]" 指定多个分隔符(包含空格)的时候,连续的空格被分隔成了多个字段。
awk 默认以空白字符(包含空格、TAB 字符、换行符)做为分隔符,为了更直观对比,此处示例直接通过 -F 参数指定。简单示例对比下:
我们先指定空格做为分隔符来获取第二个字段
# awk -F " " ‘{print NF, $2}‘ file.txt
2 root:x:0:0:root:/root:/bin/bash
2 bin:x:1:1:bin:/bin:/sbin/nologin
2 daemon:x:2:2:daemon:/sbin:/sbin/nologin
再通过 []
指定空格分隔符来获取
# awk -F "[ ]" ‘{print NF, $6}‘ file.txt
6 1 root:x:0:0:root:/root:/bin/bash
6 2 bin:x:1:1:bin:/bin:/sbin/nologin
6 3 daemon:x:2:2:daemon:/sbin:/sbin/nologin
是不是好奇怪,我们通过 -F " "
做为分隔符的时候,每行只有 2 个字段,而通过 -F "[ ]"
做分隔符的时候,每行共有 6 个字段。$1-$5
获取的值为空,而 $6
确打印了全部内容。
查看 awk 手册:4.5.1 Whitespace Normally Separates Fields
awk interpreted this value in the usual way, each space character would separate fields, so two spaces in a row would make an empty field between them. The reason this does not happen is that a single space as the value of FS is a special case—it is taken to specify the default manner of delimiting fields.
If FS is any other single character, such as ",", then each occurrence of that character separates two fields. Two consecutive occurrences delimit an empty field. If the character occurs at the beginning or the end of the line, that too delimits an empty field. The space character is the only single character that does not follow these rules.
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.
这两段内容刚好解释了这个奇怪的现象。大概意思就是:
" "
时,awk 首先从记录中去除行首和行尾的空白,然后再分割字段。-F "[ ]"
指定,执表示通过单个空格分隔,此时,将失去其做为默认分隔符的特性,与其它字符一样,遵守同样的分隔规则。结合上面内容,我们再来看几个示例,对今天的内容做个总结。
示例:
总结:
标签:special space inf 没有 ofo lines expr ret software
原文地址:https://blog.51cto.com/wuyanc/2506734