awk将打印所有列从第n个到最后用空格 [英] awk to print all columns from the nth to the last with spaces

查看:803
本文介绍了awk将打印所有列从第n个到最后用空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下输入文件:

a 1  o p
b  2 o p p
c     3 o p p  p

在最后一行有最后之间的双空间P的
和列有不同的间距

in the last line there is a double space between the last p's, and columns have different spacing

我用从溶液:<一href=\"http://stackoverflow.com/questions/2961635/using-awk-to-print-all-columns-from-the-nth-to-the-last\">Using AWK打印从第n个所有列到最后。

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

和它工作得很好,直到它到达最后一列双层空间,并删除一个空格。

and it works fine, untill it reaches double-space in the last column and removes one space.

我怎样才能避免这种情况,同时还用awk?

How can I avoid that while still using awk?

推荐答案

GNU SED

删除前n领域

sed -r 's/([^ ]+ +){2}//' file

GNU AWK 4.0 +

GNU awk 4.0+

awk '{sub("([^"FS"]"FS"){2}","")}1' file

GNU AWK&LT; 4.0

GNU awk <4.0

awk --re-interval '{sub("([^"FS"]"FS"){2}","")}1' file

柜面FS一个不工作(编辑建议)

Incase FS one doesn't work(Eds suggestion)

awk '{sub(/([^ ] ){2}/,"")}1' file

替换2要删除字段数

Replace 2 with number of fields you wish to remove

的另一种方法(不需要重新间隔)

Another way(doesn't require re-interval)

awk '{for(i=0;i<2;i++)sub($1"[[:space:]]*","")}1' file

进一步编辑

诚如通过EdMorton它是坏的使用领域子,因为它们可能含有元字符,所以这里是一个另类(又来了!)

As advised by EdMorton it is bad to use fields in sub as they may contain metacharacters so here is an alternative(again!)

awk '{for(i=0;i<2;i++)sub(/[^[:space:]]+[[:space:]]*/,"")}1' file

输出

o p
o p p
o p p  p

这篇关于awk将打印所有列从第n个到最后用空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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