Chinaunix

标题: awk的RS [打印本页]

作者: 失落之岛    时间: 2011-07-16 22:30
标题: awk的RS
# cat awk.txt
Jimmy the Weasel
100 Pleasant Drive
San Francisco, CA 12345
Big Tony
200 Incognito Ave.
Suburbia, WA 67890

BEGIN {
    FS="\n"
    RS=""
}
{
    print $1 ", " $2 ", " $3
}


在上面这段代码中,将 FS 设置成 "\n" 告诉 awk 每个字段都占据一行。通过将 RS 设置成 "",还会告诉 awk 每个地址记录都由空白行分隔。一旦 awk 知道是如何格式化输入的,它就可以为我们执行所有分析工作,脚本的其余部分很简单。让我们研究一个完整的脚本,它将分析这个地址列表,并将每个记录打印在一行上,用逗号分隔每个字段。
此代码将产生以下输出:

Jimmy the Weasel, 100 Pleasant Drive, San Francisco, CA 12345
Big Tony, 200 Incognito Ave., Suburbia, WA 67890
----------------------------------------------------------------
请问这句 通过将 RS 设置成 "",还会告诉 awk 每个地址记录都由空白行分隔。 我感觉明明是空分割,怎么是空白行分割呢 不理解,还有我用上面的代码的测试结果是
Jimmy the Weasel, 100 Pleasant Drive, San Francisco, CA 12345

有劳明白的给解释下 ,先表示感谢
作者: yinyuemi    时间: 2011-07-17 00:26
回复 1# 失落之岛


   
  1. 请问这句 通过将 RS 设置成 "",还会告诉 awk 每个地址记录都由空白行分隔。 我感觉明明是空分割,怎么是空白行分割呢 不理解,还有我用上面的代码的测试结果是
  2. Jimmy the Weasel, 100 Pleasant Drive, San Francisco, CA 12345
复制代码


你要的答案就在你提到的问题中,因为你的文本中没有空行,所以没有行分割,这样的话在RS=""的情况下,所以的文本只有一行内容。
你可以在第3行和第4行之间加个空白行,再试试你的代码。
至于为什么RS=“”,还要按空白行分割,这是龟腚

RS == "\n" Records are separated by the newline character (‘\n’). In effect, every line in the data file is a separate record, including blank lines. This is the default.
RS == any single character Records are separated by each occurrence of the character. Multiple successive occurrences delimit empty records.
RS == "" Records are separated by runs of blank lines. When FS is a single character, then the newline character always serves as a field separator, in addition to whatever value FS may have. Leading and trailing newlines in a file are ignored.
RS == regexp Records are separated by occurrences of

作者: Shell_HAT    时间: 2011-07-17 00:37
回复 1# 失落之岛


测试数据妨碍了你对这个问题的理解
#cat urfile
Jimmy the Weasel
100 Pleasant Drive
San Francisco, CA 12345

Big Tony
200 Incognito Ave.
Suburbia, WA 67890
#awk 'BEGIN{FS="\n";RS=""}{print $1 ", " $2 ", " $3}' urfile
Jimmy the Weasel, 100 Pleasant Drive, San Francisco, CA 12345
Big Tony, 200 Incognito Ave., Suburbia, WA 67890

作者: 失落之岛    时间: 2011-07-17 15:35
非常感谢2位的回答,睡的真晚,生活还是尽量规律点吧 身体才是最重要的。




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2