2010-05-19 26 views
0

好日子,解析一個CSV文件中提取一些值,但不是所有的

我有值的本地CSV文件改變人們稱爲DailyValues.csv
我需要提取類別2和類別4的值字段。
然後合併,排序並從提取的值中移除重複項(如果有)。
然後將其保存到新的本地文件NewValues.txt。

這裏是DailyValues.csv文件的例子:

category,date,value 
category1,2010-05-18,value01 
category1,2010-05-18,value02 
category1,2010-05-18,value03 
category1,2010-05-18,value04 
category1,2010-05-18,value05 
category1,2010-05-18,value06 
category1,2010-05-18,value07 
category2,2010-05-18,value08 
category2,2010-05-18,value09 
category2,2010-05-18,value10 
category2,2010-05-18,value11 
category2,2010-05-18,value12 
category2,2010-05-18,value13 
category2,2010-05-18,value14 
category2,2010-05-18,value30 
category3,2010-05-18,value16 
category3,2010-05-18,value17 
category3,2010-05-18,value18 
category3,2010-05-18,value19 
category3,2010-05-18,value20 
category3,2010-05-18,value21 
category3,2010-05-18,value22 
category3,2010-05-18,value23 
category3,2010-05-18,value24 
category4,2010-05-18,value25 
category4,2010-05-18,value26 
category4,2010-05-18,value10 
category4,2010-05-18,value28 
category4,2010-05-18,value11 
category4,2010-05-18,value30 
category2,2010-05-18,value31 
category2,2010-05-18,value32 
category2,2010-05-18,value33 
category2,2010-05-18,value34 
category2,2010-05-18,value35 
category2,2010-05-18,value07 

我發現一些有用的分析的例子在http://www.php.net/manual/en/function.fgetcsv.php,並設法提取值列的所有值,但不知道如何將其限制爲僅提取category2/4的值,然後對重複進行排序和清理。

解決方案需要在php,perl或shell腳本中。

任何幫助將不勝感激。
預先感謝您。

回答

0

這是一個shell腳本解決方案。

egrep 'category4|category2' input.file | cut -d"," -f1,3 | sort -u > output.file 

我用cut命令只是爲了告訴你,你只能提取某些列,因爲f開關切斷選擇,要提取的列。

u開關用於排序使得輸出是唯一的。

編輯: 則需要使用egrep而不是grep是很重要的,因爲grep採用了一定的限制正則表達式集合,並egrep的有幾分進一步設施

編輯(的人誰只有可用的grep):

grep 'category2' input.file > temp.file && grep 'category4' input.file >> temp.file && cut temp.file -d"," -f1,3 | sort -u > output.file && rm temp.file 

它產生相當的開銷,但仍然工程...

+0

謝謝dare2be大加讚賞。 'cut'部分單獨工作(對我而言是新的), ,但是當我使用帶egrep的完整命令來執行限制時,它會生成一個空文件。 – Yallaa 2010-05-19 04:44:49

+0

現在很奇怪。查看,檢查我是否將它從終端正確地複製到了SO,我將其複製並粘貼到終端,並且它工作正常...您確定已安裝了egrep嗎?檢查用'其中egrep' – 2010-05-19 04:50:08

+0

它安裝 ' >其中egrep命令 /bin中/ egrep的 > LS -l/bin中/ egrep的 lrwxrwxrwx 1根根3月4日1 2008 /斌/ egrep的 - >用grep ' 我試過grep和egrep,同樣的東西沒有輸出。 – Yallaa 2010-05-19 05:01:23

相關問題