任何人都知道我不能一次只更换一个短语吗? 假设我有一个带有短语的txt文件,要替换的短语例如:
111 , 232
122 , 324
依旧......
左边的每个短语都需要用右边的短语替换,每个新的替换都在一个新的行中。有没有办法从加载txt文件而不是逐个令人沮丧的替换中替换多个短语?
答案 0 :(得分:0)
根据您的情况,您希望以不同的方式处理此问题。如果适用于您的工作环境,我会接受Raihan的建议。如果适用,您也可以在vim中进行替换。如果你必须使用一个批处理脚本,这应该有所帮助,虽然它不在我的头脑中,可能需要你的一些调整,因为没有Windows机器来测试它:
setlocal enabledelayedexpansion
set new_file=your_new_or_temporary_file.txt
set name_of_your_txt_file_of_replacements=your_replacements_file_name.txt
set name_of_your_txt_file_of_content_to_replace=your_file_of_content_to_replace.txt
if EXIST "!new_file!" del "!new_file!"
for /f 'eol=; tokens=1,2 delims=,' %%l in ('type "!name_of_your_txt_file_of_replacements!"') do (
set existing_text=%%l
set replacement_text=%%i
@REM: Based on your example you will have trailing and leading blanks
@REM: See this site to trim your existing_text and replacement_text
@REM: Source: http://www.dostips.com/DtTipsStringManipulation.php
for /f "tokens=* delims= " %%a in ("!replacement_text!") do set replacement_text=%%a
for /l %%a in (1,1,31) do (
if "!existing_text:~-1!"==" " set existing_text=!existing_text:~0,-1!
if "!replacement_text:~-1!"==" " set replacement_text=!replacement_text:~0,-1!
)
echo replacing !existing_text! with !replacement_text!...
for /f 'eol=; tokens=1 delims=' %%c in ('type "!name_of_your_txt_file_of_content_to_replace!"') do (
set line=%%c
for /f 'eol=; tokens=1 delims=' %%c in ('echo !line! ^| findstr /i /c:"!existing_text!"') do (
for /f 'eol=; tokens=1,2 delims=,' %%c in ("!existing_text!,!replacement_text!") do
set line=!line:%%c=%%d!
)
@REM::Just reread your specs, and if you want the new file to just contain
@REM:: the replacement text, then do this instead:
@REM:: echo !replacement_text! >> !new_file!
@REM::Otherwise, copy of existing file with updated text
echo !line! >> !new_file!
)
)
@REM:: Compare your original file with !new_file! and make sure it is all good.
@REM:: Once you have to code to where it is all good do this
mv "!new_file!" "!name_of_your_txt_file_of_content_to_replace!"
如果您遇到问题请告诉我。祝好运! :)