批处理脚本:读取目录中的每个文件,替换一些字符串,将每个文件缩短为 10 行



我需要帮助在Windows上编写批处理脚本。我的目录 C:\OUTFiles 包含 2355 个.txt文件,这些文件具有各种长度,其中包含指向维基百科文章的链接 - 例如一个名为"Holzhausen.txt"的文件:

http://de.wikipedia.org/wiki/[[Holzhausen (Langenpreising)]], Ortsteil der Gemeinde [[Langenpreising]]http://de.wikipedia.org/wiki/[[Holzhausen (Dähre)]], Ortsteil der Gemeinde [[Dähre]]...

我想遍历 C:\OUTFiles 中的所有文件,并将每个文件的长度削减为 10 行(或者如果短于 10 行,则不要更改长度)。

此外,如果文件包含[[一些文本]],如上面第一行所示,我需要删除所有括号[[ ]]。

如何在 Windows 上将其作为批处理脚本文件执行?我是批处理脚本的新手,我搜索了 StackOverflow 并尝试组装批处理脚本,但它还没有完全完成/工作:

@ECHO OFF
setlocal enabledelayedexpansion
set counter=1
for %%f in (*.txt) do call :p "%%f"
goto :eof
:p
SET /A maxlines=10
SET /A linecount=0
FOR /F %%A IN (*.txt) DO ( 
  IF !linecount! GEQ %maxlines% GOTO ExitLoop
  ECHO %%A 
  SET /A linecount+=1
)
SET /A counter+=1

:ExitLoop
:eof

暂停

提前非常感谢!!佩特拉

此解决方案假设您购买我上面的建议以使用 powershell 而不是批处理。

# this line assumes current directory - adjust to point to the actual location
$files = get-childitem *.txt
foreach ($file in $files) {
    $data = get-content $file
    $count = 1
    # this assumes that you want to put the modified 
    # output in a new file and keep the original file
    $newfile = $file.name + ".new.txt"
    foreach ($line in $data) {
        if($count -gt 10) {break}
        $line = $line -replace "[[]]",''
        out-file -filepath $newfile -inputobject $line -Append
        $count = $count + 1
    }
}

最新更新