gpt4 book ai didi

Windows 批处理 : How to keep empty lines with loop for/f

转载 作者:行者123 更新时间:2023-12-03 11:04:09 25 4
gpt4 key购买 nike

我正在搜索如何在使用 for 循环浏览文件时保留空行。

for /f "tokens=1* delims=[" %%i in ('type "test1.txt" ^| find /v /n ""') do (
SET tmp=%%i
echo !tmp! >> test2.txt
)
实际上它适用于所有人,但就我而言,它不起作用。
例如,如果 test1.txt 内容是:
Hello I come from France
I live in Paris

I'm sorry I don't know English, could we speak French please?
If it doesn't bother you

Thank you
test2.txt 中的结果将是:
[1 
[2
[3
[4
[5
[6
[7
如果我把星号“*”附近的“1”去掉,结果是:
[1]Hello I come from France 
[2]I live in Paris
[3]
[4]I'm sorry I don't know English, could we speak French please?
[5]If it doesn't bother you
[6]
[7]Thank you
期望的输出是:
Hello I come from France
I live in Paris

I'm sorry I don't know English, could we speak French please?
If it doesn't bother you

Thank you
你能帮我解决这个问题吗?

最佳答案

这可以作为

@echo off
setlocal enableextensions disabledelayedexpansion

for /f "tokens=1,* delims=]" %%a in ('
find /n /v "" ^< "file1.txt"
') do (
>> "file2.txt" echo(%%b
)

内部 find 命令的输出类似于
[123]texttexttext

该代码使用右括号作为分隔符,因此标​​记(我们请求两个标记: 1,*1* )是
[123 texttexttext
^ ^
1 2
%%a %%b

但是,由于重复的定界符仅作为一个定界符处理,如果一行以右括号开头,它将被删除。这是可以预防的
作为

@echo off
setlocal enableextensions disabledelayedexpansion

for /f "tokens=1,* delims=0123456789" %%a in ('
find /n /v "" ^< "file1.txt"
') do (
set "line=%%b"
setlocal enabledelayedexpansion
>>"file2.txt" echo(!line:~1!
endlocal
)

在这里,数字用作分隔符,并且该行被标记为
[   ]texttexttext
^ ^
%%a %%b

然后将第二个标记的值存储在变量中,禁用延迟扩展以避免数据内部出现感叹号问题(如果延迟扩展处于事件状态,则将由解析器处理/替换)

一旦数据在变量中,延迟扩展被激活(需要一些东西,因为我们想要从代码块内更改的变量中检索内容)以从第二个位置输出行(字符串中的第一个字符为 0)以删除右括号。完成后,延迟扩展将再次禁用。

编辑 因为 OP 必须将其合并到更大/复杂的脚本中,此代码应该面临最常见的问题

@echo off
rem For this test we will have delayed expansion from the start
setlocal enableextensions enabledelayedexpansion

rem External code block that will make delayed expansion necessary
if 1==1 (
rem Variables changed inside block
set "input_file=file1.txt"
set "output_file=file2.txt"

rem Grab a reference to the content of the file variables
for %%i in ("!input_file!") do for %%o in ("!output_file!") do (

rem Prepare the environment for file work
setlocal disabledelayedexpansion

rem Prepare output file
type nul > "%%~fo"

rem Process input file and write to output file
for /f "tokens=1,* delims=0123456789" %%a in ('
find /n /v "" ^< "%%~fi"
') do (
set "line=%%b"
setlocal enabledelayedexpansion
>>"%%~fo" echo(!line:~1!
endlocal
)

rem Restore the previous environment
endlocal
)
)

关于Windows 批处理 : How to keep empty lines with loop for/f,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31314203/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com