2013-03-12 77 views
24

我有一个三列的文件。我想删除第三列(就地编辑)。我如何用awk或sed来做到这一点?用awk或sed删除一列

123 abc 22.3 
453 abg 56.7 
1236 hjg 2.3 

所需的输出

123 abc 
453 abg 
1236 hjg 
+2

我很疑惑:为了推广Ed Morton的回答,我打开了一个赏金计划,到目前为止,这些日子里[最赚钱](http://stackoverflow.com/posts/15361632/timeline)的帖子一直是个问题,它没有显示任何研究(@ _ @)'。 – fedorqui 2016-07-07 14:31:24

回答

12

这可能会为你工作(GNU SED):

sed -i -r 's/\S+//3' file 

如果你想删除的第三场之前的空白:

sed -i -r 's/(\s+)?\S+//3' file 
+0

非常感谢。 – user2160995 2013-03-12 13:21:51

+1

@potong,是'\ S'意思是不是空格的所有字符?记录在哪里? – 2013-03-12 13:37:51

+1

什么是'-r'呢?我的sed没有它。 – 2015-02-18 12:55:36

11

看来,你可以简单地用

awk '{print $1 " " $2}' file 

去打印在你的输入文件中每一行的前两个字段,其中一个空格隔开。

+2

这个假设只有3列。否则你需要一个循环:'awk'{printf $ 1 OFS $ 2; for(i = 4; i <= NF; i ++)printf OFS $ i; printf ORS}文件(OFS默认为空格,ORS默认为换行符)。 – 2016-07-06 00:57:34

7

试试这个:

awk '$3="";1' file.txt > new_file && mv new_file file.txt 

awk '{$3="";print}' file.txt > new_file && mv new_file file.txt 
44

试试这个简短的事情:

awk '!($3="")' file 
+2

+ +1为更好的awk答案。 – 2013-03-12 13:27:49

+23

这实际上并没有删除给定的列;它将它设置为空字符串,但您仍然会在输出中获得额外的'FS'。这可能或不重要,取决于您对转换数据所做的操作。 – larsks 2014-03-17 14:04:59

+0

尝试此操作以将生成的输出保存到新文件。 awk'!($ 3 =“”)'file> newfile – 2015-04-09 20:05:27

5

GNU AWK 4.1

awk -i inplace NF-- 

这将删除每一行的最后一个字段。

+0

谢谢!!非常直观:) – 2017-02-22 08:51:03

21

随着GNU AWK用于就地编辑,\s/\Sgensub()删除

1)的第一个字段:

awk -i inplace '{sub(/^\S+\s*/,"")}1' file 

awk -i inplace '{$0=gensub(/^\S+\s*/,"",1)}1' file 

2)LAST字段:

awk -i inplace '{sub(/\s*\S+$/,"")}1' file 

awk -i inplace '{$0=gensub(/\s*\S+$/,"",1)}1' file 

3)的N个字段,其​​中N = 3:

awk -i inplace '{$0=gensub(/\s*\S+/,"",3)}1' file 

没有GNU awk的你需要一个match() + substr()组合或多个sub() S +瓦尔以除去中间领域。另见Print all but the first three columns

+2

你有这样的标准答案是非常好的:) – fedorqui 2016-07-01 13:29:32

+2

注意:在Ubuntu上Trusty GNU Awk 4.0.1没有默认启用'awk' inplace扩展。 – 2016-07-07 01:41:30

0

尝试使用剪切...它的快速和容易

首先,你必须反复的空间,你可以列之间挤那些到一个单一的空间,如果这就是你想要tr -s ' '

什么?如果每列已经拥有它之间只是一个分隔符,你可以使用cut -d ' ' -f-2打印字段(列)< = 2

例如,如果你的数据是在一个文件input.txt中,你可以做下列操作之一:如果你更好

cat input.txt | tr -s ' ' | cut -d ' ' -f-2 

或者原因这个问题通过删除第三列,你可以写出下面

cat input.txt | tr -s ' ' | cut -d ' ' --complement -f3 

切是非常强大的,你也可以从手册页中提取字节或字符的范围,除了列

摘录关于如何指定名单范围

Each LIST is made up of one range, or many ranges separated by commas. 
Selected input is written in the same order that it is read, and is 
written exactly once. Each range is one of: 

    N  N'th byte, character or field, counted from 1 
    N- from N'th byte, character or field, to end of line 
    N-M from N'th to M'th (included) byte, character or field 
    -M from first to M'th (included) byte, character or field 

这样的语法,你也可以说你想要特定的列1和2 ...

cat input.txt | tr -s ' ' | cut -d ' ' -f1,2