# 关于使用ORS，NR，FS，RS的awk命令的说明

``````1
2
3
4
5
6
``````

``````awk 'ORS=NR%3?FS:RS'

1 2 3
4 5 6
``````

`ORS`=输出记录分隔符-这是我们希望最终输出的rs，它是一行3列
`NR%3`=我们希望将数据分组为3行元素
`?FS:RS`-不确定这是如何适应命令的。

`%`是模运算符（参见https://en.wikipedia.org/wiki/Modulo_operation），而`NR%3?FS:RS`是三元表达式（参见https://en.wikipedia.org/wiki/%3F:）。这些都是许多编程语言中的常见结构，它们不是awk特有的。关于ors、nr、fs和rs的含义，请参见awk手册页。

``````\$ cat tst.awk
BEGIN {
printf "%s=\"%s\"\n", "RS", RS
printf "%s=\"%s\"\n", "FS", FS
}
{
printf "---\n"

printf "%s=\"%s\"\n", "\$0", \$0
printf "%s=\"%s\"\n", "NR", NR
printf "%s=\"%s\"\n", "NR%3", NR%3

printf "before) %s=\"%s\"\n", "ORS", ORS

ORS = (NR%3 ? FS : RS)

printf "after) %s=\"%s\"\n", "ORS", ORS
}
``````

``````\$ awk -f tst.awk file
RS="
"
FS=" "
---
\$0="1"
NR="1"
NR%3="1"
before) ORS="
"
after) ORS=" "
---
\$0="2"
NR="2"
NR%3="2"
before) ORS=" "
after) ORS=" "
---
\$0="3"
NR="3"
NR%3="0"
before) ORS=" "
after) ORS="
"
---
\$0="4"
NR="4"
NR%3="1"
before) ORS="
"
after) ORS=" "
---
\$0="5"
NR="5"
NR%3="2"
before) ORS=" "
after) ORS=" "
---
\$0="6"
NR="6"
NR%3="0"
before) ORS=" "
after) ORS="
"
``````

``````\$ cat tst.awk
{
if (NR%3 == 0) {
ORS = "\n"
}
else {
ORS = " "
}

print
}

\$ awk -f tst.awk file
1 2 3
4 5 6
``````

``````awk '{ORS=(NR%3?FS:RS)}1'
``````