用awk或sed删除一列

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

123 abc 22.3 453 abg 56.7 1236 hjg 2.3 

期望的输出

 123 abc 453 abg 1236 hjg 

这可能适用于你(GNU sed):

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

如果要删除第三个字段之前的空格:

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

试试这个简短的东西:

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

用GNU awk就地编辑, \s/\Sgensub()来删除

1)第一个领域:

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

要么

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

2)最后一个字段:

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

要么

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

3)N = 3的 N场:

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

没有GNU awk,你需要一个match() + substr()组合或多个sub() s + vars来删除一个中间字段。 另请参阅打印除前三列之外的所有内容 。

看来你可以简单地去

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

这会在input文件中打印每行的两个第一个字段,并用空格分隔。

尝试这个 :

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

要么

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

GNU awk 4.1

 awk -i inplace NF-- 

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

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

首先你有多个空格,你可以将它们压缩到列之间的单个空格,如果这就是你想要的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 

剪切function非常强大,除了列以外,还可以提取字节或字符的范围

从手册页摘录如何指定列表范围的语法

 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 NM 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