我正在尝试将给定目录中的文件夹名称分配给不同的变量。
我可以在UNIX中执行相同的操作,但是很难从批处理中实现。下面是unix代码。在文件changed.txt中,行数如下:
branches/abc/xyz/components/ADAdapter/release/post_commit_hook.zip branches/abc/xys/components/ADAdapter/release/post_commit_hook.zip branches/abc/xyz/components/ADAdapter/release/post_commit_hook.zip branches/abc/xyz/components/ADAdapter/release/post_commit_hook.zip
for x in `cat changed.txt`
do
a=`echo $x |egrep -i 'release'|egrep -i 'zip'| sed 's/.*release\///'|
sed 's/^[ \t]*//;s/[ \t]*$//' `
b="$b,$a"
c=`echo $x | cut -d "/" -f1`
d=`echo $x | cut -d "/" -f5`
e="$e,$c"
f="$f,$d"
done
PACKAGE=`echo $b | sed 's/[,]//'`
BRANCH=`echo $e | sed 's/[,]//'`
UPDATEFOLDER=`echo $f | sed 's/[,]//'`
echo PACKAGE is $PACKAGE
echo BRANCH is $BRANCH
echo UPDATEFOLDER is $UPDATEFOLDER
我期望这个输出
PACKAGE is post_commit_hook.zip,post_commit_hook.zip,post_commit_hook.zip,post_commit_hook.zip BRANCH is branches,branches,branches,branches UPDATEFOLDER is ADAdapter,ADAdapter,ADAdapter,ADAdapter
有人可以帮我做批处理吗?
答案 0 :(得分:0)
这是一个基于我的评论的示例:
@Echo Off
SetLocal EnableDelayedExpansion
Rem This Undefines the variables
For %%A In (PKG BRN UPD) Do Set "%%A="
Rem This will propagate the variables
For /F "Tokens=1,5,7 Delims=/" %%A In (
'FindStr /I "\/release/.*\.zip$" "changed.txt"'
) Do (
If Defined BRN (Set "BRN=!BRN!,%%A") Else Set "BRN=%%A"
If Defined UPD (Set "UPD=!UPD!,%%B") Else Set "UPD=%%B"
If Defined PKG (Set "PKG=!PKG!,%%C") Else Set "PKG=%%C"
)
Rem This will show the variables with their content
For %%A In (PKG BRN UPD) Do Set %%A 2>Nul
Pause
[编辑/]
由于acronicks的注释,如果文件使用LF
行尾或未以标准CRLF
结尾,那么此版本就足够了。它还会更改变量名称以使其与问题中的变量名称匹配。
@Echo Off
SetLocal EnableDelayedExpansion
Rem This Undefines the variables
For %%A In (PACKAGE BRANCH UPDATEFOLDER) Do Set "%%A="
Rem This will propagate the variables
For /F "Tokens=1,5,7 Delims=/" %%A In (
'More "changed.txt"^|FindStr /I "\/release/.*\.zip$"'
) Do (
If Defined BRANCH (Set "BRANCH=!BRANCH!,%%A") Else Set "BRANCH=%%A"
If Defined UPDATEFOLDER (Set "UPDATEFOLDER=!UPDATEFOLDER!,%%B") Else Set "UPDATEFOLDER=%%B"
If Defined PACKAGE (Set "PACKAGE=!PACKAGE!,%%C") Else Set "PACKAGE=%%C"
)
Rem This will show the variables with their content
Echo PACKAGE is %PACKAGE%
Echo BRANCH is %BRANCH%
Echo UPDATEFOLDER is %UPDATEFOLDER%
Pause
[Edit2 /]
这是一个小小的修改,允许先将命令保存到变量中,然后再注释。
@Echo Off
SetLocal EnableDelayedExpansion
Rem This Undefines the variables
For %%A In (PACKAGE BRANCH UPDATEFOLDER) Do Set "%%A="
Rem This will propagate the variables
Set "a=More "changed.txt"|FindStr /I "\/release/.*\.zip$""
For /F "Tokens=1,5,7 Delims=/" %%A In ('"%a%"') Do (
If Defined BRANCH (Set "BRANCH=!BRANCH!,%%A") Else Set "BRANCH=%%A"
If Defined UPDATEFOLDER (Set "UPDATEFOLDER=!UPDATEFOLDER!,%%B") Else Set "UPDATEFOLDER=%%B"
If Defined PACKAGE (Set "PACKAGE=!PACKAGE!,%%C") Else Set "PACKAGE=%%C"
)
Rem This will show the variables with their content
Echo PACKAGE is %PACKAGE%
Echo BRANCH is %BRANCH%
Echo UPDATEFOLDER is %UPDATEFOLDER%
Pause