0
任何機構都知道一種方法,我不能一次只替換一個短語? 說我有一個短語一個txt文件,短語來代替,例如:從逗號分隔的txt文件中替換很多短語
111 , 232
122 , 324
等..需要與右邊的短語來代替
左側每個詞組並且每個新的替代品都在一個新的行中。有沒有一種方法可以替換加載一個txt文件的多個短語,而不是一個一個的令人沮喪的替換?
任何機構都知道一種方法,我不能一次只替換一個短語? 說我有一個短語一個txt文件,短語來代替,例如:從逗號分隔的txt文件中替換很多短語
111 , 232
122 , 324
等..需要與右邊的短語來代替
左側每個詞組並且每個新的替代品都在一個新的行中。有沒有一種方法可以替換加載一個txt文件的多個短語,而不是一個一個的令人沮喪的替換?
根據你的情況,你會想以不同的方式來解決這個問題。如果適用於您的工作環境,我會採取Raihan的建議。如果適用,您也可以在vim中進行替換。如果你必須使用一個批處理腳本,這應該有所幫助,但是這是我的頭頂部,並可能需要你做一些調整,因爲沒有窗戶的機器來測試它:
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!"
如果運行成問題讓我知道。祝你好運! :)
您需要使用'sed'。爲了告訴你確切的命令,我們需要更多的細節。就像一個示例輸入和輸出文件。 – Raihan
不好意思。我想我不明白你需要什麼。你是在談論*兩個*文件,其中一個帶有多個替換短語(如上所述)和*另一個*文件以及您想要處理的文本?如果是這樣,什麼「和每個新的替代品在一個新的行」是什麼意思?如Raihan所建議的那樣,發佈一個樣本輸入和輸出。 – Aacini