[英]Print matched field separators in awk
Given the following record 鉴于以下记录
01-01-2012 18:02 some data 01-11-2014 20:22 some other data 10-02-2014 14:00 more data still
I am trying to group date, time and data and print them on separate lines like so: 我正在尝试对日期,时间和数据进行分组,并将它们打印在不同的行上,如下所示:
01-01-2012 18:02 some data
01-11-2014 20:22 some other data
10-02-2014 14:00 more data still
However, what I have so far: 但是,到目前为止我所拥有的:
echo '01-01-2012 18:02 some data 01-11-2014 20:22 some other data 10-02-2014 14:00 more data still' | awk -F '[0-9]*-[0-9]*-[0-9]* [0-9]*:[0-9]*' '{ for ( n=1; n<=NF; n++ ) print $n }
results in this: 结果如下:
some data
some other data
more data still
The dates and times are missing. 缺少日期和时间。 They are field separators, therefore they don't print.
它们是场分离器,因此它们不打印。
How can I modify my awk script in order to print every field separator that matches the regex? 如何修改我的awk脚本以打印与正则表达式匹配的每个字段分隔符?
Using gnu awk: 使用gnu awk:
awk -v RS='[0-9]+-[0-9]+-[0-9]+ [0-9]+:[0-9]+' '!NF{s=RT;next} {print s $0}' file
01-01-2012 18:02 some data
01-01-2012 18:02 some other data
01-01-2012 18:02 more data still
EDIT: Using non-gnu awk you can do: 编辑:使用非gnu awk你可以做:
awk '{gsub(/[[:blank:]]+[0-9]+-[0-9]+-[0-9]+ [0-9]+:[0-9]+/, "\n&");
gsub(/\n[[:blank:]]+/, "\n")} 1' file
01-01-2012 18:02 some data
01-11-2014 20:22 some other data
10-02-2014 14:00 more data still
Also using grep -P
you can do: 同样使用
grep -P
你可以这样做:
grep -oP '[0-9]+-[0-9]+-[0-9]+ [0-9]+:[0-9]+.+?(?=[0-9]+-[0-9]+-[0-9]+|$)' file
01-01-2012 18:02 some data
01-11-2014 20:22 some other data
10-02-2014 14:00 more data still
awk方式
awk '{for(i=2;i<=NF;i++)if($i~/[0-9]+-[0-9]+-[0-9]+/)$i="\n"$i}1' file
by awk 通过awk
awk '{for (i=1;i<=NF;i++) printf ($i~/-..-/)?RS $i:FS $i}' infile
for loop
: read the element one by one, elements are splitted by whitespace. for loop
:逐个读取元素,元素按空格分割。 printf
: print the element without return printf
:打印元素而不返回 printf ($i~/-..-/)?RS $i:FS $i
- can be expended to if-else statement: if ($i~/-..-/) {print RS $i) else (print FS $i)
printf ($i~/-..-/)?RS $i:FS $i
- 可以用于if-else语句: if ($i~/-..-/) {print RS $i) else (print FS $i)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.