我现在对脚本还不熟悉,但我发现理解“for”命令真的很难(尤其是那些标记和分隔符等)。话虽如此,我认为 for 命令可以用来做我正在做的事情。如果不是,而且有更简单的方法,请忽略我的无知 :(
假设我在文本文件 abc.txt 中有多行,每行都以“(引号)开头和结尾,例如一个包含 3 行的文件
"hey what is going on @mike220. I am working on your car. Its engine is in very bad condition"
"Because if you knew, you'd get shredded and do it with certainty"
"@honey220 Do you know someone who has busted their ass on a diet only for results to come to a screeching halt after a few weeks"
我如何将引号内的每一行修剪为固定长度,例如 30 或 50 或 100 个字符(包括空格) 我想批量输入字符数,它可以相应地进行修剪并生成一个带有引号内修剪行的文件 def.txt。
假设我输入 50,上述示例的结果应该是
"hey what is going on @mike220. I am working on you"
"Because if you knew, you'd get shredded and do it"
"@honey220 Do you know someone who has busted their"
谢谢
PS 如果您使用 For 命令,请解释该命令。
编辑: 虽然提供的答案有效,但非英语文本存在问题。我在输入文件中的非英语文本的输出文件中得到了乱码。任何帮助@barlop这里是非英语文本(1行)
"फाइल है इसको ना पढ़े आपको कोई मतलांब नही"
答案1
这样做
@echo off
setlocal enableextensions enabledelayedexpansion
set /p num=Enter chars to show between quotes:
set /a num=%num%+1
for /f "delims=" %%f in (a.txt) do (
set a=%%f
echo !a:~0,%num%!^"
)
因此,使用您的示例,它在 a.txt 中,因此每一行都以引号开头,并且也有空格,但如果没有空格它也可以工作。
"hey what is going on @mike220. I am working on your car. Its engine is in very bad condition"
"Because if you knew, you'd get shredded and do it with certainty"
"@honey220 Do you know someone who has busted their ass on a diet only for results to come to a screeching halt after a few weeks"
并运行批处理脚本
C:\blah>a.bat
Enter chars to show between quotes: 3
"hey"
"Bec"
"@ho"
C:\blah>a.bat
Enter chars to show between quotes: 50
"hey what is going on @mike220. I am working on you"
"Because if you knew, you'd get shredded and do it "
"@honey220 Do you know someone who has busted their"
C:\blah>
我现在添加了两行,使其输出到文件 def.txt
@echo off
setlocal enableextensions enabledelayedexpansion
del def.txt 2>nul
set /p num=Enter chars to show between quotes:
set /a num=%num%+1
for /f "delims=" %%f in (a.txt) do (
set a=%%f
echo !a:~0,%num%!^"
echo !a:~0,%num%!^" >>def.txt
)
C:\crp\dlsnex>a
Enter chars to show between quotes: 2
"he"
"Be"
"@h"
C:\crp\dlsnex>type def.txt
"he"
"Be"
"@h"
C:\crp\dlsnex>
for
cmd 中的语句有点棘手。要理解这一点,只需开始尝试编写一个 for 语句,打印文件的每一行,不进行修剪,并使用一个简单的文件,例如包含两行 abcdefg 和 hijklmn 的文件。然后使用这个 for 语句,for /f %f in (a.txt) do @echo %f
然后就可以构建它了。但是,如果您要弄清楚如何做到这一点,那就是您的起点。一旦有了它,添加“delims=”看看它有什么效果(您可能需要在文件的行中留出一些空格才能看到效果)。然后看看如何批量获取子字符串。set a=abcdefg echo %a:~0,2%(打印 ab)。