繁体   English   中英

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

[英]Find a string and replace specific letters in batch file

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

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

疯狐狸跳下老藤,踢足球。

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

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

谢谢,乔伊

@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%"

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

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

使用 REPL.BAT:

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

我有时使用它: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
@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.

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM