如何在文件中搜索特定数据并在批处理文件中替换它旁边的字符串

时间:2020-12-28 19:22:07

Hello I am trying to search particular string in file and want to replace that string with other string in batch file.

您好我正在尝试搜索文件中的特定字符串,并希望将该字符串替换为批处理文件中的其他字符串。

For example, I am having a.txt containing following data:

例如,我有一个包含以下数据的a.txt:

line 1: Name: abc
line 2: Some words then age: 24 something
line 3: country:xyz

Now i want to find with "age:" and want to replace to

现在我想找到“年龄:”并想要替换为

line 2: Some words then age: 30 something

and save in same a.txt.

并保存在相同的a.txt中。

thanks for help

感谢帮助

1 个解决方案

#1


0  

This will replace every instance of age: (whatever) in a text.inf with age: 30:

这将取代text.inf中的每个年龄实例:(无论如何)年龄:30:

for /f "tokens=1* delims=: " %%x in (text.inf) do (
  if "%%x"=="age" (
    echo %%x: 30 >> outfile.tmp
  ) else (
    echo %%x: %%y >> outfile.tmp
  )
)
move /y outfile.tmp text.inf

OK, your new specs make this more difficult, but...

好的,你的新规格让这更难,但......

setlocal enabledelayedexpansion
set line=
for /f "tokens=* delims= " %%x in (text.inf) do call :workit %%x
move /y outfile.tmp text.inf
endlocal
goto :eof

:workit
set line=
  :workitloop
  set line=!line! %1
  if "%1"=="age:" (
    set line=!line! 30
    shift
    shift
    goto :workitloop
  ) else if "%1"=="" (
    echo !line:~1!>> outfile.tmp
  ) else (
    shift
    goto :workitloop
  )
goto :eof

#1


0  

This will replace every instance of age: (whatever) in a text.inf with age: 30:

这将取代text.inf中的每个年龄实例:(无论如何)年龄:30:

for /f "tokens=1* delims=: " %%x in (text.inf) do (
  if "%%x"=="age" (
    echo %%x: 30 >> outfile.tmp
  ) else (
    echo %%x: %%y >> outfile.tmp
  )
)
move /y outfile.tmp text.inf

OK, your new specs make this more difficult, but...

好的,你的新规格让这更难,但......

setlocal enabledelayedexpansion
set line=
for /f "tokens=* delims= " %%x in (text.inf) do call :workit %%x
move /y outfile.tmp text.inf
endlocal
goto :eof

:workit
set line=
  :workitloop
  set line=!line! %1
  if "%1"=="age:" (
    set line=!line! 30
    shift
    shift
    goto :workitloop
  ) else if "%1"=="" (
    echo !line:~1!>> outfile.tmp
  ) else (
    shift
    goto :workitloop
  )
goto :eof