2012-12-07 37 views
0

我有很多行日食.classpath文件像如何在bash shell腳本中將一部分字符串提取到變量中?

<classpathentry kind="lib" path="/somepath/somelibrary.jar"/> 

我的本意是寫一個bash腳本,將解析各行測試,如果庫中存在。對於獎勵積分,由於我知道我的機器上可能存在該庫的備用位置,因此如果在類路徑文件指定的位置找不到該位置,則我還將搜索備用位置並儘可能修復類路徑文件。

我該怎麼做?

好像How can I extract part of a string via a shell script?是相關的,但不知道如何把它變成一個格式,與

#!/bin/sh 
while read f 
do 
    if [ -f $f ] 
    then 
     echo "Found: $f" 
    else 
     echo "Missing: $f" 
    fi 
done < $1 

我認爲這是我的目標。

+1

我可以建議蟒蛇,紅寶石,PHP ...? –

+0

正如@KarolyHorvath所提到的,你可能會更好地使用python,ruby,php等解決方案。 Bash可能不是解析xml最理想的方法。由於'.classpath'恰好是xml格式,所以你可以使用'xpath'。你可以嘗試使用'xpath -q -e classpath/classpathentry [@kind = \「lib \」]/@ path | cut -d'='-f2 | tr -d來獲取路徑列表'''''或其他更好的東西 –

+0

事實上,我很樂意用任何語言來做這件事,我不熟悉(或者不夠熟悉)任何提到完成這項工作的人。我追求的任務...高興地驗證你的工作:)我目前正在追逐bash版本,並且很快就會用我的腳本的當前狀態更新這個問題。 – joewyrembelski

回答

2
sed -n 's/.*path="\([^"]*\)".*/\1/p' file | 
while IFS= read -r file 
do 
    if [ -f "$f" ] 
    then 
     echo "Found: $f" 
    else 
     echo "Missing: $f" 
    fi 
done 

它不適用於包含換行符或雙引號的文件名。如果你有任何一個讓我們知道。

+2

如果是標準XML,雙引號將是編碼爲'"'。 – anishsane

+0

@anishsane - 感謝您的信息。 –

0

使用egrep先將jar路徑從類路徑文件中取出,然後遍歷每個路徑。

for f in $(egrep -o '[/a-zA-Z0-9]+\.jar' .classpath); do 
    if [ -f $f ] 
    then 
     echo "Found: $f" 
    else 
     echo "Missing: $f" 
    fi 
done 
相關問題