2015-10-15 144 views
1

我有我的批處理腳本輸入未知長度的文件的URL。如何在批量中將URL拆分爲其組成部分?

http://Repository.com/Stuff/Things/Repo/file1.csv

http://www.place.com/Folder/file2.xml

很少有與他們根本沒有一致性。我只需要一種使用批處理的方式(儘管從批處理中調用powershell是一種選擇)將它們分解爲完整路徑和文件名。

http://Repository.com/Stuff/Things/Repo/

http://www.place.com/Folder/

file1.csv

file2.xml

我見過許多其他語言做這件事的方式,但我有限的一批,和這不是我強大的語言之一。我試着用「delims = /」使用far/f循環,但是當它到達//時退出。

回答

3
@echo off 
setlocal EnableDelayedExpansion 

set "url=http://Repository.com/Stuff/Things/Repo/file1.csv" 

for %%a in ("%url%") do (
    set "urlPath=!url:%%~NXa=!" 
    set "urlName=%%~NXa" 
) 
echo URL path: "%urlPath%" 
echo URL name: "%urlName%" 

輸出:

URL path: "http://Repository.com/Stuff/Things/Repo/" 
URL name: "file1.csv" 
+0

這一個沒有做出多語言的陳述就是我今天想要的。謝謝。 –

+0

我認爲做echo「'%%〜DPa」可以做到這一點。 – Paul

+0

@保羅:不,它不起作用。看到阿卜杜拉的回答如下... – Aacini

0

使用字符串類的splitSubString方法。

例如

$filename = $url.split('/')[-1] 
# $url.split('/') splits the url on the '/' character. [-1] takes the last part 
$rest = $url.SubString(0, $url.Length - $filename.Length) 
# The first parameter is the starting index of the substring, the second is the length. 
2

在PowerShell中,你可以投URL字符串System.Uri類提供有關URL及其結構的大量信息。您可能需要Uri.Segments財產的工作情況如下:

PS C:\> # get System.Uri object: 
PS C:\> $uri = [uri]"http://Repository.com/Stuff/Things/Repo/file1.csv" 
PS C:\> $uri 


AbsolutePath : /Stuff/Things/Repo/file1.csv 
AbsoluteUri : http://repository.com/Stuff/Things/Repo/file1.csv 
LocalPath  : /Stuff/Things/Repo/file1.csv 
Authority  : repository.com 
HostNameType : Dns 
IsDefaultPort : True 
IsFile   : False 
IsLoopback  : False 
PathAndQuery : /Stuff/Things/Repo/file1.csv 
Segments  : {/, Stuff/, Things/, Repo/...} 
IsUnc   : False 
Host   : repository.com 
Port   : 80 
Query   : 
Fragment  : 
Scheme   : http 
OriginalString : http://Repository.com/Stuff/Things/Repo/file1.csv 
DnsSafeHost : repository.com 
IsAbsoluteUri : True 
UserEscaped : False 
UserInfo  : 



PS C:\> # get base URL without page name and query parameters: 
PS C:\> $uri.Scheme + ":/" + $uri.Authority + (-join $uri.Segments[0..($uri.Segments.Length - 2)]) 
http:/repository.com/Stuff/Things/Repo/ 
PS C:\> # get page/file name: 
PS C:\> $uri.Segments[-1] 
file1.csv 
+0

這可以在powershell ise中使用,但是我無法像powershell -command那樣工作($ uri = [uri]「%url%」; $ uri.Segments [-1])。我正在嘗試將其整合到一個完成剩餘工作的批處理解決方案中。 –

0
@echo off 
Set input=http://Repository.com/Stuff/Things/Repo/file1.csv 
SETLOCAL ENABLEDELAYEDEXPANSION 
For %%A in ("%input%") do (
    Set url= %%~pA 
    set url=!url:~2! 
    Set fileName=%%~nxA 
) 
echo.URL is: %url% 
echo.File Name is: %fileName% 
ENDLOCAL 


輸出

enter image description here

+0

感謝您獲得第一批純粹的批處理解決方案,但正斜槓會更改爲反斜槓,並且第一組將更改爲單個批處理解決方案。這會弄亂腳本的其餘部分。 –