批处理(bat)中的数组问题 您所在的位置:网站首页 字符串数组有二维的吗 批处理(bat)中的数组问题

批处理(bat)中的数组问题

2024-03-15 16:09| 来源: 网络整理| 查看: 265

在这里插入图片描述

文章目录 数组创建数组访问数组遍历数组求数组长度数组结构体 总结

最近在弄jenkins,需要用到bat command,就到处找相关问题,期间学到一些东西,有也踩过一些坑,这里借助CSDN记录下来,总结下学到的知识和解决的问题。

2

数组 创建数组

数组在批处理脚本中没有专门定义为类型,但是可以实现。当在批处理脚本中实现数组时,需要注意以下事项。

需要用set命令定义数组的每个元素。需要使用’ for '循环来遍历数组的值。

使用下面的set命令创建一个数组:

set a[0]=1

另一种实现数组的方法是定义值列表并遍历值列表。下面的示例展示了如何实现这一点

@echo off set list=1 2 3 4 (for %%a in (%list%) do ( echo %%a ))

输出结果:

1 2 3 4 Press any key to continue . . .

这个知识点帮我解决一个棘手的问题: 问题背景: 上层传给我一个路径字符串 内容是四个文件 分别以分好分割 a/file1.txt;b/file2.tx2;c/file3.txt;d/file4.txt 我需要提取这四个文件并且做性对应的处理,这里我需要解决两个问题,字符串路径的分割处理和数组的循环

@echo off set filelist=a/file1.txt;b/file2.tx2;c/file3.txt;d/file4.txt for %%a in (%filelist%) do ( echo %%~nxa) pause

输出结果:

file1.txt file2.tx2 file3.txt file4.txt Press any key to continue . . .

说明: %%~n 代表文件名 %%~x 代表文件扩展名 %%~nx 代表文件名和扩展名这里是引用

访问数组

可以使用下标语法从数组中检索值,将要检索的值的索引直接在方括号中传递到数组的名称之后。

@echo off set a[0]=1 set a[1]=2 set a[2]=3 echo The first element of the array is %a[0]% echo The second element of the array is %a[1]% echo The third element of the array is %a[2]%

输出结果:

The first element of the array is 1 The second element of the array is 2 The third element of the array is 3 遍历数组

通过使用’ for '循环并遍历数组中的每个元素来实现对数组的迭代。下面的例子展示了一种实现数组的简单方法。

@echo off setlocal enabledelayedexpansion set topic[0]=comments set topic[1]=variables set topic[2]=Arrays set topic[3]=Decision making set topic[4]=Time and date set topic[5]=Operators for /l %%n in (0,1,5) do ( echo !topic[%%n]! ) pause

输出结果:

The first element of the array is 1 The second element of the array is 2 The third element of the array is 3

for /l %%n in (0,1,5) 这行代码是for 循环的一种使用方式 for /L %%变量 in (起始值,每次增值,结束时的比较值) do 命令 , in (0,1,5) 会生成一个序列 [0,1,2,3,4],具体参考bat for in用法

求数组长度

数组的长度是通过迭代数组中的值列表来完成的,因为没有直接函数来确定数组中的元素数量。

@echo off set Arr[0]=1 set Arr[1]=2 set Arr[2]=3 set Arr[3]=4 set "x=0" :SymLoop if defined Arr[%x%] ( call echo %%Arr[%x%]%% set /a "x+=1" GOTO :SymLoop ) echo "The length of the array is" %x% pause

输出结果:

1 2 3 4 "The length of the array is" 4 Press any key to continue . . . 数组结构体

结构也可以在批处理文件中实现,使用一点额外的代码来实现。下面的示例展示了如何实现这一点。

@echo off set obj[0].Name=Joe set obj[0].ID=1 set obj[1].Name=Mark set obj[1].ID=2 set obj[2].Name=Mohan set obj[2].ID=3 FOR /L %%i IN (0 1 2) DO ( call echo Name = %%obj[%%i].Name%% call echo Value = %%obj[%%i].ID%% ) pause

输出结果:

Name = Joe Value = 1 Name = Mark Value = 2 Name = Mohan Value = 3 Press any key to continue . . .

23

总结

7

在这里插入图片描述

要有最朴素的生活,最遥远的梦想,即使明天天寒地冻,路遥马亡!如果这篇博客对你有帮助,请 “点赞” “评论”“收藏”一键三连 哦!码字不易,大家的支持就是我坚持下去的动力。当然执意选择白嫖也欢迎。 18


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有