免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
论坛 程序设计 Shell awk的RS
最近访问板块 发新帖
查看: 3399 | 回复: 3
打印 上一主题 下一主题

awk的RS [复制链接]

论坛徽章:
1
IT运维版块每日发帖之星
日期:2016-04-30 06:20:00
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-07-16 22:30 |只看该作者 |倒序浏览
# 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

有劳明白的给解释下 ,先表示感谢

论坛徽章:
2
射手座
日期:2014-10-10 15:59:4715-16赛季CBA联赛之上海
日期:2016-03-03 10:27:14
2 [报告]
发表于 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

论坛徽章:
33
ChinaUnix元老
日期:2015-02-02 08:55:39CU十四周年纪念徽章
日期:2019-08-20 08:30:3720周年集字徽章-周	
日期:2020-10-28 14:13:3020周年集字徽章-20	
日期:2020-10-28 14:04:3019周年集字徽章-CU
日期:2019-09-08 23:26:2519周年集字徽章-19
日期:2019-08-27 13:31:262016科比退役纪念章
日期:2022-04-24 14:33:24
3 [报告]
发表于 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

论坛徽章:
1
IT运维版块每日发帖之星
日期:2016-04-30 06:20:00
4 [报告]
发表于 2011-07-17 15:35 |只看该作者
非常感谢2位的回答,睡的真晚,生活还是尽量规律点吧 身体才是最重要的。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP