2012-11-14 33 views
-1

這裏切的基本路徑是我想抓住這是繼基本路徑的例子如何使用正則表達式

SF_Library/example/Platform/Analyses-PLATFORM.part0.xml 
SF_Library/example/Platform/Models-PLATFORM.part0.xml 
SF_Library/example/Platform/Models-PLATFORM.car 
SF_Library/example/Platform/DS-PLATFORM.car 

SF_Library/example/Platform/ 

有人知道我應該使用哪種正則表達式嗎?

+0

從內存:分配i = /你的/路徑/到/文件然後做'echo $ {i ## * /}'。 –

+0

爲什麼在問題上反對投票?它有什麼問題? – Satish

+0

缺乏研究和缺乏顯示你的嘗試,我猜。 –

回答

4

的正則表達式是不是提取子串。爲什麼不使用dirname命令?

$ dirname /home/foo/whatever.txt 
/home/foo 
$ 

如果你需要在一個變量:

DIRECTORY=`basename "SF_Library/example/Platform/DS-PLATFORM.car"` 
+0

酷!它更簡單,然後預期。 – Satish

+0

@Satish嗯,這是Unix ... ;-) – 2012-11-14 20:49:15

6

你並不需要一個正則表達式:

#!/bin/bash 

fullpath="SF_Library/example/Platform/Analyses-PLATFORM.part0.xml" 
# or if you read them then: while read fullpath; do 

basename=${fullpath%/*} 

# or if you read them then: done < input_file.txt 
2

您可以使用dirname命令:

dirname SF_Library/example/Platform/DS-PLATFORM.car 

它會給你:SF_Library/example/Platform

1

好吧,我會放縱你。

^(.*/).*$ 

夾層:

^  beginning of string 
( start of capture group 
    .* series of any number of any character 
/ a slash 
)  end of capture group 
.* series of any number of characters that are not slashes 
$  end of string 

這工作,因爲*是貪婪的:它儘可能多的字符相匹配,因爲它可以(這樣將包括所有的斜槓一直到最後一個)。

但正如其他答案指出的,正則表達式可能不是最好的方式來做到這一點。

+0

哦,爲什麼,爲什麼......? – 2012-11-14 20:43:40