2013-03-12 78 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