Windows 批处理脚本:子串计算
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6275233/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Windows batch script: substring calculation
提问by Mohamed Saligh
I have a situation like this. I have a list of urls in a file.
我有这样的情况。我有一个文件中的网址列表。
SET str1="http://www.domain.com/dir1/dir2/dir3/dir4/dir5/file1.txt"
SET str1="http://www.domain.com/dir1/dir2/dir3/dir4/dir5/file1.txt"
In the above string http://www.domain.com/dir1/dir2/dir3
is constant in all the urls.
I need to extract the rest of the path in each url.
上面的字符串http://www.domain.com/dir1/dir2/dir3
在所有 url 中都是常量。我需要提取每个 url 中的其余路径。
I mean, i need to get the final string from the above url is /dir4/dir5/file1.txt
我的意思是,我需要从上面的 url 中获取最终字符串是 /dir4/dir5/file1.txt
Thanks
谢谢
回答by Gabe
You need the %var:~start,end%
notation. For example, if you run this:
你需要%var:~start,end%
符号。例如,如果你运行这个:
@SET str1="http://www.domain.com/dir1/dir2/dir3/dir4/dir5/file1.txt"
@ECHO %str1:~37,-1%
It will print /dir4/dir5/file1.txt
.
它会打印/dir4/dir5/file1.txt
。
回答by Helen
Alternatively, you can use the %variable:str_to_delete=%
syntax to delete a character string from the variable. This way you don't have to rely on the character positions within the string.
或者,您可以使用%variable:str_to_delete=%
语法从变量中删除字符串。这样您就不必依赖字符串中的字符位置。
Example code:
示例代码:
@echo off
set str1="http://www.domain.com/dir1/dir2/dir3/dir4/dir5/file1.txt"
:: remove the common part of the path
set str2=%str1:http://www.domain.com/dir1/dir2/dir3=%
:: remove the quotes
set str2=%str2:"=%
echo.%str2%
Output:
输出:
/dir4/dir5/file1.txt