查找字符串并用不同的字符串替换每个匹配项

时间:2011-03-03 14:09:27

标签: list batch-file replace

我正在寻找以下简单的批处理解决方案:

在许多文件中,我想用另一个文件替换一个字符串。可以使用Notepad ++完成此操作。但是,每个新字符串必须是唯一的,从新字符串列表中读取。

所以,如果某些文件中出现“abc”,并且我有一个包含新字符串的列表,请以这种方式替换它:

abc - >亚历克斯
abc - >本
abc - >克里斯
abc - >戴夫
等。

我可以有一个带有新字符串的txt文件来读取。

希望有人为我找到解决方案!

非常感谢, 伦纳特

3 个答案:

答案 0 :(得分:2)

Perl脚本会起作用吗?

my @words = qw(alex ben chris dave ...);

while (<>) {
    s/abc/shift @words/ge;
    print;
}

如果你想要单词列表循环:

my @words = qw(...);
my $i = 0;

while (<>) {
    # I know I should have written this in a more readable way...
    s{abc}{$words[$i++] // $words[$i=0]}ge;
    print;
}

答案 1 :(得分:1)

或作为批处理脚本

@echo off
setlocal Disabledelayedexpansion
set "wordlist=alex ben chris dave"
for /F "tokens=* delims=" %%a in (myFile.txt) do (
    set "line=%%a"
    setlocal Enabledelayedexpansion
    for /F "tokens=1,*" %%b in ("!wordlist!") do (
        set "newline=!line:abc=%%b!"
        (echo(!newline!)
        if !newline! NEQ !line! (
            endlocal
            set "wordlist=%%c"
        ) ELSE ( 
            endlocal 
        )
    )   
)

修改更改为“!”安全的变种

答案 2 :(得分:0)

尝试找到支持sed-i)切换的Windows --inline可执行文件,您的工作将成为幼儿的任务!

相关问题