2017-07-30 19 views
0

我的查詢是我有一個csv文件,有11列。我想提取具有7列數字的記錄。請注意第7列有字符串以及數字。使用awk命令但沒有工作如何過濾unix中的列

+1

請與你已經嘗試沿着預期的輸出張貼一些樣本數據。 –

回答

1

如果我明白了,你想要7列作爲數字的行?

你可以使用grep來做到這一點。隨着 '' 作爲分隔符:

grep ".*,.*,.*,.*,.*,.*,[0-9]*,.*" yourfile.csv 

如果你想只有7列,利用切割(-D =>分隔符,-f選擇字段)

cat yourfile | cut -d, -f7 | grep "[0-9]*" 
0

我不知道,如果你'特別尋找一個bash命令,但我建議使用像python這樣的腳本語言。這樣做在Python的方法之一是:

count = 0 
prunedColumns = [] 
with open('FILENAME','r') as f: 
    for line in f: 
     count = 0 
     for entry in line.split(','): 
      try: 
       float(entry) 
       count += 1 
      except ValueError: 
       continue 
      if count == 7: 
       prunedColumns.append(line) 
print(prunedColumns) 
+0

比方說,該文件是: ABC; 123; AAAA; 789 PQR; 567; 5555; 999 的Xyz; 888; BBBB; 6453 LMN; 777; 5555; 8989 我期待輸出有第2列(第3列只有數字) – shikha

0

首先是一些測試數據:

$ cat file 
1 2 3 4 5 6 7 a b c d # seven numbers, a hit 
1 2 3 4 5 6 a b c d e # six, a miss 
1 2 3 4 5 6 7 8 a b c # eight, a miss 
1 2 3 4 5 6 7a b c d e # seven, a hit 

在awk中:

$ awk '{ 
    for((i=1)&&c=0;i<=NF;i++) # check each field 
     if($i~/[0-9]+/)  # if there are numbers in it 
      c++    # iterate counter 
} 
c==7       # if there are 7 fields, print record 
' file      
1 2 3 4 5 6 7 a b c d # seven numbers, a hit 
1 2 3 4 5 6 7a b c d e # seven, a hit 
0

嘗試多途徑這裏,使用相同的INPUT_FILE作爲詹姆斯·布朗在他的帖子中使用。

awk '{val=$0;if(gsub(/[0-9]+/,"",val)==7){print}}' Input_file 

輸出如下。

1 2 3 4 5 6 7 a b c d # seven numbers, a hit 
1 2 3 4 5 6 7a b c d e # seven, a hit 
+0

我正在尋找第7列,具體有一些行中的數字和其他列中的字符串 – shikha

+0

@shikha:您可以添加示例Input_file和預期的輸出到您的文章中的代碼標籤,這對我們來說很有幫助。 – RavinderSingh13

0
cat file.csv | awk '{print $7}'| egrep -v [a-z]+