查找字符串并替换批处理文件中的特定字母

时间:2013-06-13 11:12:38

标签: string search batch-file

我有一个创建自动作业的工作来触发一个批处理文件,该文件会找到一个特定的字符串,然后替换接下来的4个字符。

例如,如果文件(包含多行)的内容低于内容而我正在搜索播放

疯狂的狐狸跳过了老藤蔓 踢足球。

我应该用“INFA”替换“socc”

我是批处理文件的新手,我的主管一直坚持只使用批处理文件。任何帮助都会得到很大的帮助。

谢谢, 喜悦

5 个答案:

答案 0 :(得分:5)

@echo off &setlocal
set "search=search string"
set "replace=kordo anstataui"
set "textfile=file.txt"
set "newfile=new.txt"

(for /f "delims=" %%i in ('findstr /n "^" "%textfile%"') do (
    set "line=%%i"
    setlocal enabledelayedexpansion
    set "line=!line:%search%=%replace%!"
    echo(!line!
    endlocal
))>"%newfile%"
type "%newfile%"

答案 1 :(得分:2)

显然你正在搜索最后用空格“玩”,虽然你的问题有点模糊。

查看我的hybrid JScript/batch utility called REPL.BAT进行正则表达式搜索和替换。它适用于从XP开始的任何现代版Windows,并且不需要安装任何第三方可执行文件。

使用REPL.BAT:

type "yourFile.txt"|repl "played ...." "played INFA" >"yourFile.txt.new"
move /y "yourFile.txt.new" "yourFile.txt" >nul

答案 2 :(得分:1)

我有时会使用它:sar.bat

::Search and replace
@echo off
if "%~3"=="" (
echo.Search and replace
echo Syntax: 
echo "%~nx0" "filein.txt" "fileout.txt" "regex" "replace_text" [first]
echo.
echo.EG: change the first time apple appears on each line, to orange
echo."%~nx0" "my text old.txt" "my text changed.txt" "apple" "orange" first
echo.
echo.People that are familiar with regular expressions can use some:
echo.
echo.Change every line starting from old (and everything after it^) to new
echo."%~nx0" "my text old.txt" "my text changed.txt" "old.*" "new"
echo.
echo.If [first] is present only the first occurrence per line is changed
echo.
echo.To make the search case sensitive change
echo.IgnoreCase= from True to False
echo.
pause
goto :EOF
)
if "%~5"=="" (set global=true) else (set global=false)
set s=regex.replace(wscript.stdin.readall,"%~4")
 >_.vbs echo set regex=new regexp
>>_.vbs echo regex.global=%global%
>>_.vbs echo regEx.IgnoreCase=True
>>_.vbs echo regex.pattern="%~3"
>>_.vbs echo wscript.stdOut.write %s%
cscript /nologo _.vbs <"%~1" >"%~2"
del _.vbs

答案 3 :(得分:1)

@echo off
setlocal EnableDelayedExpansion

set "search=played "
set replacement=INFA
set numChars=4

set line=the mad fox jumped of the old vine and played soccer. 

rem The characters after the equal-signs are Ascii-254
for /F "tokens=1* delims=■" %%a in ("!line:%search%=■!") do (
   set "rightPart=%%b"
   set "line=%%a%search%%replacement%!rightPart:~%numChars%!"
)

echo !line!

输出:

the mad fox jumped of the old vine and played INFAer.

您必须将以前的代码插入到处理整个文件的循环中。我把那部分留给你做练习......

答案 4 :(得分:0)

sed获取your OS的副本,并从批处理文件中调用它。

sed -e 's/socc/INFA/g' inputFileName > outputFileName