我想编写一个批处理脚本,以便转到特定目录,并为每个文本文件在每行的末尾添加空间,以使每行(col)大小为50。它应该更新同一文件而不是创建一个新文件。
示例:我有5
个文件,file1
,file2
,file3
,file4
和file5
。每个文件都有多行,例如file1
中有3
行:
lin 1 (length of line 27)
line 2 (length of line 37)
line 3 (length of line 47)
file1
的末尾输出应为:
lin 1 (length of line 50)
line 2 (length of line 50)
line 3 (length of line 50)
通过在行尾添加空格。每行的所有文件都应重复相同的操作。
@ECHO OFF
ECHO lets start
REM set current path
set pathname="C:\Users\Desktop\New folder"
REM Change the Directory
cd /d %Pathname%
echo Directory changed to %Pathname%
for %%x in (*.txt) do (
echo %%x
for /f " tokens=* delims= " %%a in (%%x) do (
echo %%a
)
)
PAUSE
答案 0 :(得分:0)
这是一个批处理脚本,可以满足您的需要(请检查代码中的rem
备注):
@echo off
setlocal EnableExtensions DisableDelayedExpansion
rem // Define constants here:
set "PATHNAME=C:\Users\Desktop\New folder" & rem // (root directory)
set "SPACES= " & rem // (50 spaces)
set "TRUNC=#" & rem // (set empty to not truncate lines longer than 50 char.s)
rem // Enumerate matching files:
for %%F in ("%PATHNAME%\*.txt") do (
rem // Write to temporary file:
> "%%~F.tmp" (
rem // Read a file line by line (empty lines are skipped):
for /F usebackq^ delims^=^ eol^= %%L in ("%%~F") do (
rem // Store current line:
set "LINE=%%L"
setlocal EnableDelayedExpansion
rem // Check whether line is not longer than 50 char.s:
if "!LINE:~,50!"=="!LINE!" (
rem // Not longer, so pad with spaces, then truncate:
set "LINE=!LINE!%SPACES%"
echo(!LINE:~,50!
) else (
rem // Longer, so check whether to truncate or keep:
if defined TRUNC (
echo(!LINE:~,50!
) else (
echo(!LINE!
)
)
endlocal
)
)
rem // Replace original file by temporary one:
> nul move /Y "%%~F.tmp" "%%~F"
)
endlocal
exit /B
您应该在检查之前备份文件,因为输入的文本文件已被替换。