如何从UNIX平面文件解析奇数场? [英] How to parse odd numbered fields from a flat file in unix?

查看:91
本文介绍了如何从UNIX平面文件解析奇数场?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个平面文件,我想从所有行解析奇数列出来。

I have a flat file and I want to parse odd numbered columns out of it from all the rows.

我很新的UNIX和我走近的方式是这样的。

I am quite new to UNIX and the way I approached is this

awk 'BEGIN{ FS = OFS = "|" } { for (i=2;i<=NF;i++) { if(i%2==0) { print $i }}}' newProcessFile.txt

显然,这是不产生所需的输出。
我究竟做错了什么?请解释 。

Obviously it is not producing the required output. What am I doing wrong ? Please explain .

推荐答案

您可以做到这一点 AWK

awk '{for (i=1;i<=NF;i+=2) printf "%s ",$i;print ""}' file

这将打印每一秒列。

It will print every second columns.

cat file
one
one two
one two three
one two three four
one two three four five
one two three four five six

awk '{for (i=1;i<=NF;i+=2) printf "%s ",$i;print ""}' file
one
one
one three
one three
one three five
one three five


使用其它的分隔符:


With other separators:

cat file
one
one|two
one|two|three
one|two|three|four
one|two|three|four|five
one|two|three|four|five|six

awk -F\| '{s="";for (i=1;i<=NF;i+=2) {s=s?s FS $i:$i} print s}' file
one
one
one|three
one|three
one|three|five
one|three|five

这篇关于如何从UNIX平面文件解析奇数场?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆