无法使用批处理文件重写txt文件

Posted

技术标签:

【中文标题】无法使用批处理文件重写txt文件【英文标题】:not working batch file to rewrite txt file 【发布时间】:2021-05-10 00:34:07 【问题描述】:

我正在使用 devcon 实用程序创建一个文件,以便列出所有连接到 PC 的 USB 设备,因为我需要删除隐藏设备(未使用)。此时我想重写创建文件中的字符串,但将“@”添加到字符串的开头和“直到字符串的结尾,所以这将是一个示例

devcon 得到的字符串

USB\VID_8087&PID_0025\7&21809D95&0&2

希望重写

"@USB\VID_8087&PID_0025\7&21809D95&0&2"

不确定是否可以在同一行中完成,或者是否需要单独添加

setlocal
cmd /c "for /f delims^=^ eol^= %%I in ('findstr /c:"USB\VID" DevicesExist.txt') do @for %%a in (%%I) do @echo %%a"| findstr /c:"USB\VID">DevicesExist2.txt

有什么想法吗?谢谢

【问题讨论】:

我对三件事感到困惑。 1) 你为什么使用CMD /C?你为什么要使用第二个FOR 命令? 3) 你为什么要使用第二个FINDSTR 命令与第一个命令做同样的事情?您甚至没有尝试在代码中输出您想要的数据。我在您的代码中没有看到您尝试输出前导引号和符号的任何位置。 【参考方案1】:
@ECHO OFF
SETLOCAL
rem The following settings for the source directory, destination directory, target directory,
rem batch directory, filenames, output filename and temporary filename [if shown] are names
rem that I use for testing and deliberately include names which include spaces to make sure
rem that the process works using such names. These will need to be changed to suit your situation.

SET "destdir=u:\your results"
SET "outfile=%destdir%\outfile.txt"

(
FOR /f "tokens=1delims= " %%b IN ('devcon findall *^|find "USB\VID"') DO (
 ECHO "@%%b"

)
)>>"%outfile%"

GOTO :EOF

不太清楚为什么您的代码如此复杂,或者为什么您没有发布您的DevicesExist.txt 文件的小样本。

此代码执行devcon 并将处理后的提取数据附加到目标文件。使用 > 代替 >> 将目标文件的任何现有内容替换为此批处理的输出。

【讨论】:

以上是关于无法使用批处理文件重写txt文件的主要内容,如果未能解决你的问题,请参考以下文章

如何使用批处理或PowerShell从文本文件中删除换行符

无法使用 grunt copy-task 处理文件

使用特定文件夹中的批处理文件创建 txt 文件

使用 undertow 文件处理程序重写 URL

比较两个文件夹的批处理?

使用多行将字符串回显到 .txt 文件 - 使用 Windows 批处理文件