2

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

例如,如果文件(多行)具有以下内容并且我正在搜索已播放

疯狐从老藤上跳下来踢足球。

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

我是批处理文件的新手,我的领导一直坚持我只使用批处理文件来执行此操作。任何帮助将不胜感激。

谢谢,乔伊

4

5 回答 5

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%"
于 2013-06-13T12:18:55.033 回答
2

显然,您正在搜索末尾有空格的“played”,尽管您的问题有点含糊。

请参阅我的名为 REPL.BAT 的混合 JScript/批处理实用程序,它执行正则表达式搜索和替换。它适用于从 XP 开始的任何现代版本的 Windows,并且不需要安装任何第 3 方可执行文件。

使用 REPL.BAT:

type "yourFile.txt"|repl "played ...." "played INFA" >"yourFile.txt.new"
move /y "yourFile.txt.new" "yourFile.txt" >nul
于 2013-06-13T12:08:27.607 回答
2

我有时使用这个: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
于 2013-06-13T12:02:07.837 回答
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.

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

于 2013-06-13T17:34:14.850 回答
1

您的操作系统获取一份sed副本,然后从批处理文件中调用它。

sed -e 's/socc/INFA/g' inputFileName > outputFileName
于 2013-06-13T11:19:16.690 回答