使用批处理脚本进行字符串处理
我当前正在创建一个批处理脚本,该脚本必须循环遍历文件中的行,检查某些字符串,以及是否存在带有“#”的匹配前缀(将其注释掉)。
我对批处理脚本完全陌生,到目前为止我所得到的只是:
for /f %%j in (CMakeLists.txt) do (
if "%%j"=="Extensions_AntTweakBar" (
echo lol1
)
if "%%j"=="Extensions_Inspection" (
echo lol2
)
if "%%j"=="Extensions_InspectionBar" (
echo lol3
)
)
所以我当前的问题是,我不知道如何在批处理脚本中操作字符串。如果有人可以帮助我,我将不胜感激:)
I'm currently creating a batch script that has to loop through the lines in a file, checking for some string, and if theres a match prefix that string with a '#' (comment it out).
I'm perfectly new to batch script, all I got this far is:
for /f %%j in (CMakeLists.txt) do (
if "%%j"=="Extensions_AntTweakBar" (
echo lol1
)
if "%%j"=="Extensions_Inspection" (
echo lol2
)
if "%%j"=="Extensions_InspectionBar" (
echo lol3
)
)
So my current issue is, I don't know how to operate on string within batch scripts. If someone could help me out that would be appreciated :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通常,您可以只使用要附加的文本,后跟变量。
如果你只是做回声,那很好。
echo #%%j
将满足您的需求。但如果你想将该行设置为变量,则必须 启用延迟扩展。将
setlocal ENABLEDELAYEDEXPANSION
添加到文件顶部,然后用!
而不是%
包围变量。例如(请注意,我添加了delims=
将整行放入%%j
而不是该行的第一个单词):给定以下输入文件:
上面的脚本产生以下输出:
当然,删除
@echo off
将帮助您调试问题。但话虽如此,您已经达到了批处理字符串处理所能完成的极限。如果您仍然想使用批处理命令,则可能需要开始将行写入临时文件并使用
findstr
和正则表达式。You can just use the text you want to append followed by your variable generally.
If you're just doing echo, that's fine.
echo #%%j
will do what you need.But if you want to set the line to a variable, you have to enable delayed expansion. Add
setlocal ENABLEDELAYEDEXPANSION
to the top of your file and then surround your variables with!
instead of%
. For example (and notice that I've addeddelims=
to put the entire line in%%j
instead of the first word on the line):Given this input file:
The above script produces this output:
And of course removing
@echo off
will help you debug problems.But all that being said, you're about at the limit of what you can accomplish with batch string processing. If you still want to use batch commands, you may need to start writing lines to temporary files and using
findstr
with a regex.如果没有更好地了解循环中想要的内容或 CMakeLists.txt 文件的外观,请尝试以下初学者:
&&使第二个命令(ECHO)以第一个命令在没有错误状态的情况下退出为条件,并且 ||就像一个逻辑“或”,当第一个“或”不运行时它就会运行。
实际上,要修改文本文件的内部结构,您最好使用 sed 或 awk - win32 二进制文件可以在 UnxUtils 项目。
Without a better understanding of what you want inside your loop or what your CMakeLists.txt file looks like, try this on for starters:
The && makes the second command (the ECHO) conditional on the first command exiting without an error state, and the || is like a logical OR and it runs when the first one doesn't.
Really, for modifying the internals of a text file you are probably going to be much better off using either sed or awk - win32 binaries can be found in the UnxUtils project.