使用批处理,对txt文档增加、修改相关内容。要求如下: 1.将此txt文档拖入cmd窗口; 2.读取txt文档,逐行分成元素,分隔符为“,”; 3.获取txt文档行数,减去1,得到参数Txt_lines; 4.获取txt文档第Txt_lines行第一个元素的长度,得到参数Txt_lines_length; 5.获取txt文档每一行第一个元素的长度,比Txt_lines_length少多少,就在该行第一个元素第一个字符后增加多少个“0”; 6.将txt文档每一行第二个元素设为“1”; 7.将txt文档每一行第三个元素前增加“3”; 8.将txt文档每一行第四个元素前增加“83”; 9.输入一个带小数点的数字,得到参数mj; 10.在txt文档开头处新增以下内容: [描述] 大哥=北京1986年 二哥=3 三哥=上海 四哥=龙 五哥=25 六哥=0.001 七哥=,,,,,, [啥玩意] Txt_lines,mj,哥哥1,妹,,,,@ 11.生成修改后的txt文档。
时间: 2024-03-05 11:51:22 浏览: 66
以下是批处理代码实现:
```batch
@echo off
setlocal enabledelayedexpansion
REM Step 1: Drag and drop the txt file onto the cmd window to set the file path
set "filepath=%~1"
REM Step 2: Read the txt file and split into elements by comma
set /a linecount=0
for /f "tokens=1-4 delims=," %%a in (%filepath%) do (
set /a linecount+=1
set "line[!linecount!]=%%a,%%b,%%c,%%d"
)
REM Step 3: Get the line count of the txt file
set /a Txt_lines=%linecount%-1
REM Step 4: Get the length of the first element in the last line
set "lastline=!line[%linecount%]!"
set /a Txt_lines_length=0
for /f "tokens=1 delims=," %%a in ("!lastline!") do (
set "lastelement=%%a"
for /l %%i in (0,1,100) do (
if not "!lastelement:~%%i,1!"=="" set /a Txt_lines_length=%%i+1
)
)
REM Step 5: Add "0" to the end of the first element in each line
for /l %%i in (1,1,!linecount!) do (
set "line[%%i]=!line[%%i]:~0,%Txt_lines_length%!000!line[%%i]:~%Txt_lines_length%!"
)
REM Step 6: Set the second element of each line to "1"
for /l %%i in (1,1,!linecount!) do (
for /f "tokens=2 delims=," %%a in ("!line[%%i]!") do (
set "line[%%i]=!line[%%i]:%%a,=1,!"
)
)
REM Step 7: Add "3" to the beginning of the third element in each line
for /l %%i in (1,1,!linecount!) do (
for /f "tokens=1,2,* delims=," %%a in ("!line[%%i]!") do (
set "line[%%i]=%%a,%%b,3%%c"
)
)
REM Step 8: Add "83" to the beginning of the fourth element in each line
for /l %%i in (1,1,!linecount!) do (
for /f "tokens=1,2,3,* delims=," %%a in ("!line[%%i]!") do (
set "line[%%i]=%%a,%%b,%%c,83%%d"
)
)
REM Step 9: Input a number with decimal point and set it to the variable mj
set /p mj="Please input a number with decimal point: "
REM Step 10: Add new content to the beginning of the txt file
echo [描述] 大哥=北京1986年 二哥=3 三哥=上海 四哥=龙 五哥=25 六哥=0.001 七哥=,,,,,, [啥玩意] Txt_lines,mj,哥哥1,妹,,,,@ > newfile.txt
type %filepath% >> newfile.txt
REM Step 11: Generate the modified txt file
move /y newfile.txt %filepath%
echo The txt file has been modified successfully!
```
请将以上代码保存为 `modify_txt.bat` 文件,然后将需要修改的txt文件拖拽至该文件上即可执行。
阅读全文