Chinaunix

标题: awk如何利用正则来作为FS变量?(正则分隔符) [打印本页]

作者: sk1418    时间: 2011-04-27 20:37
标题: awk如何利用正则来作为FS变量?(正则分隔符)
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的值呢?
作者: ziyunfei    时间: 2011-04-27 20:47
--re-interval
作者: sk1418    时间: 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.


这不冲突了么?
作者: jason680    时间: 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}'




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