免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 4401 | 回复: 3
打印 上一主题 下一主题

awk如何利用正则来作为FS变量?(正则分隔符) [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-04-27 20:37 |只看该作者 |倒序浏览
rt, 看了TIM的awk的精华,里面讲了FS可以是正则,但没发现例子。

我今天遇到的问题,比如说下面这个文件(内容不放在code里了,因为code里加不了字体颜色)

asdff as df asdf  a  g a fas fa sdf as f asd f asdf a sdf a g gg a ds  a s df asd g sh s gas f asdf asdf asd f 04/23/11 11:22:33 a;lsdf asdf sdfh 23
jga alkj d this is a test  f 04/20/11 21:22:33 a;lsdf asdf sdfh 234 adsfa adslfkja sdflajd

文件格式很不规则,但是每行都有一个固定格式的日期时间。 我现在就要以这个日期时间来作为分隔符,来取前面的部分。

目的不是如何取到值,而是要如何用正则作为FS。


我做了如下测试了,都不行
  1. awk -F'.{2}/.{2}/.{2} .{2}:.{2}:.{2}' '{print $1}' file
  2. awk 'BEGIN{FS=".{2}/.{2}/.{2} .{2}:.{2}:.{2}"}{print $1}' file
复制代码


应该如何写这个正则,作为FS的值呢?

论坛徽章:
1
摩羯座
日期:2014-12-29 15:59:36
2 [报告]
发表于 2011-04-27 20:47 |只看该作者
--re-interval

论坛徽章:
0
3 [报告]
发表于 2011-04-27 21:00 |只看该作者
谢谢学习了这个选项,以前还真不知道。 再问一下,我查看了man awk
里面关于这个选项:
--re-interval
              Enable the use of interval expressions in regular expression matching (see Regular Expressions, below).  Interval  expressions  were  not  traditionally
              available  in the AWK language.  The POSIX standard added them, to make awk and egrep consistent with each other.  However, their use is likely to break
              old AWK programs, so gawk only provides them if they are requested with this option, or when --posix is specified.

意思就是gawk如果不用这个选项,FS就不按正则对待了。
可如果看FS部分:

Fields
       As each input record is read, gawk splits the record into fields, using the value of the FS variable as the field separator.  If  FS  is  a  single  character,
       fields  are separated by that character.  If FS is the null string, then each individual character becomes a separate field. Otherwise, FS is expected to be a
       full regular expression.


这不冲突了么?

论坛徽章:
145
技术图书徽章
日期:2013-10-01 15:32:13戌狗
日期:2013-10-25 13:31:35金牛座
日期:2013-11-04 16:22:07子鼠
日期:2013-11-18 18:48:57白羊座
日期:2013-11-29 10:09:11狮子座
日期:2013-12-12 09:57:42白羊座
日期:2013-12-24 16:24:46辰龙
日期:2014-01-08 15:26:12技术图书徽章
日期:2014-01-17 13:24:40巳蛇
日期:2014-02-18 14:32:59未羊
日期:2014-02-20 14:12:13白羊座
日期:2014-02-26 12:06:59
4 [报告]
发表于 2011-04-27 21:27 |只看该作者
rt, 看了TIM的awk的精华,里面讲了FS可以是正则,但没发现例子。

我今天遇到的问题,比如说下面这个文件 ...
sk1418 发表于 2011-04-27 20:37



$ echo 'asdff as df asdf  a 04/23/11 11:22:33 a;lsdf asdf sdfh 23' | awk -F'../../.. ..:..:..' '{print "$1="$1",$2="$2}'
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP