使用批处理替换文件中的部分文本

时间:2012-01-18 19:35:22

标签: replace batch-file

文件'MyFile.txt'中有一行,我需要替换该行的一部分。

示例:

文件中的行是这样的

53544THOIN91111160000000

我想从'MyFile.txt'中的现有行替换'111116',这里的东西是'111116'是一个变量并且会不断变化。它基本上是格式为YYMMDD的日期,我想从另一个文件读取修改日期并在'MyFile.txt'中替换这些数字

这是我试过的代码。

set b=MyFile.txt

for /f "tokens= 1" %%c in (%b%) do (set line=%%c)

Set OLDDate=%line:~11,6%

SET filename="AnotherFile.txt"
FOR %%f IN (%filename%) DO SET filedatetime=%%~tf

SET Month=%filedatetime:~0,2%
SET Date=%filedatetime:~3,2%
SET Year=%filedatetime:~8,2%

SET NEWDate=%Year%%Month%%date%

ECHO OLD DATE = %OLDDate%
ECHO NEW DATE = %NEWDate%

我需要将%OLDDate%替换为位于~11,6的“MyFile.txt”中的%NEWDate%

1 个答案:

答案 0 :(得分:0)

为什么powershell无法做到这一点?

    # Example of PowerShell -replace parameter
    clear-Host
    $file = Get-ChildItem "D:\powershell\snippets\g*.txt"
    foreach ($str in $file) 
    {
    $content = Get-Content -path $str
    $content | foreach {$_ -replace "the the", "the"} | Set-Content $str
    }
    write-Host "After replace `n"
    $file

在foreach循环中,您可以将任何字符串替换为另一个字符串。

日期逻辑可以按如下方式使用:

$anotherfile = gi anotherfile.txt

检索日期信息

$year = $anotherfile.LastWriteTime.Year
相关问题