今天用 awk 格式化字符串的時候,發現了一個奇怪現象,查看了 awk 手冊後,特以此文記錄。html
後文全部 awk 語名中出現的 file.txt
內容均以下:express
# 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 的 "[]" 指定多個分隔符(包含空格)的時候,連續的空格被分隔成了多個字段。bash
awk 默認以空白字符(包含空格、TAB 字符、換行符)作爲分隔符,爲了更直觀對比,此處示例直接經過 -F 參數指定。簡單示例對比下:app
咱們先指定空格作爲分隔符來獲取第二個字段ide
# 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
再經過 []
指定空格分隔符來獲取this
# 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
確打印了所有內容。spa
查看 awk 手冊:4.5.1 Whitespace Normally Separates Fields
code
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
orm
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 手冊htm
這兩段內容恰好解釋了這個奇怪的現象。大概意思就是:
" "
時,awk 首先從記錄中去除行首和行尾的空白,而後再分割字段。-F "[ ]"
指定,執表示經過單個空格分隔,此時,將失去其作爲默認分隔符的特性,與其它字符同樣,遵照一樣的分隔規則。結合上面內容,咱們再來看幾個示例,對今天的內容作個總結。
示例:
總結: