我想从txt文件中删除所有空格和制表符。下面是我尝试执行的代码:
for /F "delims=" %%a in (CODE_CHECK.txt) do (
set one=%%a
set one=%one:=%
) >> CODE_CHECK_2.txt
示例文件行:
ONE VIEW
TWO PACKEGE BODY
代码后应为:
ONEVIEW
TWOPACKEGEBODY
答案 0 :(得分:1)
由于您提供的代码和包含的标签,因此假设您使用的是Windows平台...
下面的batch-file示例将删除空格和制表符,还删除所有空白行:
@If Exist "CODE_CHECK.txt" (For /F Delims^=^ EOL^= %%A In ('More /T1 "CODE_CHECK.txt"')Do @Set "$=%%A"&Call Echo(%%$: =%%)>"CODE_CHECK_2.txt"
要使用batch-file保留任何空白行,您将需要以下类似内容:
@If Exist "CODE_CHECK.txt" (For /F "Tokens=1*Delims=]" %%A In ('More "CODE_CHECK.txt"^|Find /V /N ""')Do @Set "$= %%B"&Call Echo(%%$: =%%)>"CODE_CHECK_2.txt"
在此示例中,我删除了/T1
的{{1}}选项,但不确定其包含的效率是多少还是更低
您也可以使用powershell,(如果需要,输入和输出文件可以相同):
More
您还可以从powershell运行batch-file版本:
(GC 'CODE_CHECK.txt') -Replace '\s',''|SC 'CODE_CHECK_2.txt'
在此版本中,我使用了@PowerShell -NoP "(GC 'CODE_CHECK.txt') -Replace ' |\t',''|SC 'CODE_CHECK_2.txt'"
作为' |\t'
的替代方案。
答案 1 :(得分:1)
鉴于文件包含少于64K行,每个行的长度少于8K字节/字符,不需要保留空行,并且文件使用DOS / Windows风格的换行符进行ASCII / ANSI编码,您可以执行以下操作:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
rem // Write output to another file:
> "CODE_CHECK_2.txt" (
rem /* Read file by `more` which replaces TABs by SPACEs;
rem then parse the output by `for /F` (skipping empty lines): */
for /F delims^=^ eol^= %%L in ('more "CODE_CHECK.txt"') do (
rem // Store current (non-empty) line:
set "LINE=%%L"
rem /* Toggle delayed expansion to be able to write and read
rem a variable in the same block of code and to preserve `!`: */
setlocal EnableDelayedExpansion
rem // Replace every SPACE by nothing, hence remove it:
echo(!LINE: =!
endlocal
)
)
endlocal
exit /B
这是一种保留空行的方法(尽管其余限制仍然适用):
@echo off
setlocal EnableExtensions DisableDelayedExpansion
rem // Write output to another file:
> "CODE_CHECK_2.txt" (
rem /* Read file by `more` which replaces TABs by SPACEs;
rem precede every line by line number plus `:` to not appear empty;
rem then parse the output by `for /F` (which would skip empty lines): */
for /F "delims=" %%L in ('more "CODE_CHECK.txt" ^| findstr /N "^"') do (
rem // Store current line:
set "LINE=%%L"
rem /* Toggle delayed expansion to be able to write and read
rem a variable in the same block of code and to preserve `!`: */
setlocal EnableDelayedExpansion
rem // Replace every SPACE by nothing, hence remove it:
set "LINE=!LINE: =!"
rem // Remove line number prefix and return result:
echo(!LINE:*:=!
endlocal
)
)
endlocal
exit /B