2014-05-01 53 views
1

我有幾百個平面html文件,每個文件都包含一些我想要輸出到單個csv的數據。我可以在多個文件中搜索文本並將結果輸出到一個.csv文件嗎?

如:

<meta property="og:latitude" content="50.079176"> 
<meta property="og:longitude" content="-5.694866"> 

我可以遞歸grep命令查找這兩條線,輸出在CSV一條線,像這樣:

文件名,50.079176,-5.694866

這可能來自mac命令行,或者我需要一個bash腳本?或者也許咕嚕可以做到這一點?

回答

1

你真的應該使用什麼是正確的命令行HTML解析器像xidel,但這裏是一個骯髒的(非GNUawk的解決方案,應該在OS X上運行:

$ cat t.awk 
#!/usr/bin/awk -f 

function extr(s) { 
    sub(/^.+content="/, "", s); 
    sub(/".*$/, "", s); 
    return s; 
} 

/og:latitude/ && /content/ { latitude = extr($0) } 
/og:longitude/ && /content/ { longitude = extr($0); exit } 
# the above exit will speed things up but obviously requires 
# that the latitude property always precedes the longitude property 
# in your files 

END { 
    if (latitude && longitude) 
     printf "%s,%s,%s\n", FILENAME, latitude, longitude 
} 

$ find . -name "*.html" -exec ./t.awk {} \; 
bar.html,51.123456,-4.654321 
foo.html,50.079176,-5.694866 

這裏有一個bash版本,它遍歷所有.html文件在當前目錄:

#!/bin/bash 

for file in *.html; do 
    [ -f "${file}" ] || continue 
    latitude= 
    longitude= 
    while IFS= read -r line; do 
     case ${line} in 
      *og:latitude*content=*) 
       latitude=${line##*content=\"} 
       latitude=${latitude%%\"*} 
       ;; 
      *og:longitude*content=*) 
       longitude=${line##*content=\"} 
       longitude=${longitude%%\"*} 
       ;; 
      *) ;; 
     esac 
    done < "${file}" 
    [[ -n ${latitude} && -n ${longitude} ]] && echo "${file},${latitude},${longitude}" 
done 

$ ./test.sh 
bar.html,51.123456,-4.654321 
foo.html,50.079176,-5.694866 
+0

非常感謝Adrian - bash腳本像魅力一樣工作(我在for循環中添加了'find',以便我可以遞歸搜索目錄) - 現在我要看看xidel! – BellamyStudio

相關問題