2012-07-03 35 views
1

我有一些文件,在下面的格式,包括一天的股票數據的結束:如何將一組csv文件轉換爲另一組csv文件(具有不同的文件名和格式)?

文件名:NYSE_20120116.txt

<ticker>,<date>,<open>,<high>,<low>,<close>,<vol> 
A,20120116,36.15,36.36,35.59,36.19,3327400 
AA,20120116,10.73,10.78,10.53,10.64,20457600 

如何創建爲每個符號文件? 例如,對於A公司

文件名:A.TXT

<ticker>,<date>,<open>,<high>,<low>,<close>,<vol> 
A,20120116,36.15,36.36,35.59,36.19,3327400 
A,20120117,39.76,40.39,39.7,39.99,4157900 
+0

是否有可能通過更改腳本從結果文件中刪除ticker列? – skiabox

回答

2

要分割的記錄等級中的第一個文件,然後基於第一字段的值航線的每一行到不同的文件?

# To skip first line, see later 
cat endday.txt | while read line; do 
    # Careful with backslashes here - they're not quote signs 
    # If supported, use: 
    # symbol=$(echo "$line" | cut -f1 -d,) 
    symbol=`echo "$line" | cut -f1 -d,` 

    # If file is not there, create it with a header 
    # if [ ! -r $symbol.txt ]; then 
    # head -n 1 endday.txt > $symbol.txt 
    # fi 
    echo "$line" >> $symbol.txt 
done 

效率不高:Perl或Python本來會更好。

如果你在一個目錄多個文件(請注意,你必須對他們自己刪除,否則將被一次又一次地處理......),你可以這樣做:

for file in *.txt; do 
    echo "Now processing $file..." 
    # A quick and dirty way of ignoring line number 1 --- start at line 2. 
    tail -n +2 $file | while read line; do 
     # Careful with backslashes here - they're not quote signs 
     # If supported, use: 
     # symbol=$(echo "$line" | cut -f1 -d,) 
     symbol=`echo "$line" | cut -f1 -d,` 

     # If file is not there, create it with a header 
     # if [ ! -r $symbol.txt ]; then 
     # head -n 1 $file > $symbol.csv 
     # fi 
     # Output file is named .CSV so as not to create new .txt files 
     # which this script might find 
     echo "$line" >> $symbol.csv 
    done 
    # Change the name from .txt to .txt.ok, so it won't be found again 
    mv $file $file.ok 
    # or better move it elsewhere to avoid clogging this directory 
    # mv $file /var/data/files/already-processed 
done 
+0

是否可以將外部循環添加到此腳本中,以便我不必爲每個源文件執行此操作?再次感謝您。 – skiabox

+0

我收到以下消息:腳本已啓動,輸出文件是打字稿,然後我在文件夾中創建了一個小型打印稿文件。我正在用macos獅子使用bash外殼。 – skiabox

+0

我修正了(我不得不輸入./script)。現在我得到的錯誤是'./script:line 5:$ symbol.txt:模棱兩可的重定向' – skiabox

相關問題