[英]Replace nth occurence of string in each line of a text without extra software
我想替換每行上的第三個tabkey,並用冒號替換。 通過cmd在Windows中可能嗎? 我正在使用大型文本文件來進行此操作,而對於記事本++來說太大了,如果可能的話,我希望避免安裝額外的軟件
輸入
用戶名名字姓氏電子郵件號碼
產量
用戶名名姓電子郵件:號碼
由於批處理文件for循環一次處理一行,因此文件大小無關緊要。 運行可能需要一些時間,但應該完成。
TestInput.txt中的測試數據:
one two three four five six seven
1 2 3 4 5 6 7
only two tabs in this line
only one tab in this line
no tabs in this line
this line has 5 tabs in it
批處理文件使用TestInput.txt
@echo off
if exist TestOutput.txt del TestOutput.txt
SETLOCAL ENABLEDELAYEDEXPANSION
rem /f "tokens=1,2,3,4,* delims=^T" %%A in (TestInput.txt) do (
for /f "tokens=1,2,3,4,* delims= " %%A in (TestInput.txt) do (
if not "%%D"=="" (
rem The line has at least 3 tabs
rem OutputLine=%%A^T%%B^T%%C:%%D^T%%E
set OutputLine=%%A %%B %%C:%%D %%E
) else (
if not "%%C"=="" (
rem line has 2 tabs
rem OutputLine=%%A^T%%B^T%%C%%D%%E
set OutputLine=%%A %%B %%C%%D%%E
) else (
if not "%%B"=="" (
rem line has 1 tab
rem OutputLine=%%A^T%%B%%C%%D%%E
set OutputLine=%%A %%B%%C%%D%%E
) else (
rem line has no tabs
set OutputLine=%%A%%B%%C%%D%%E
)
)
)
echo !OutputLine!
echo !OutputLine!>>TestOutput.txt
)
ENDLOCAL
pause
exit
請注意,delims =之后的字符是實際的制表符。 確保您的編輯器沒有將制表符替換為空格或將Notepad.exe用於編輯器。
我不確定論壇上的帖子如何保存數據,但是%% A和%% B,%% B和%% C以及%% C和%% D之間的字符也必須是實際的制表符。
@echo off
(for /F "tokens=1-5" %%a in (input.txt) do (
if "%%e" neq "" (
echo %%a %%b %%c %%d:%%e
) else (
echo %%a %%b %%c:%%d
)
)) > output.txt
只要確保在每種情況下都在echo
命令中插入適當的分隔符即可:在%%a
和%%c
之后的TAB,在第一種情況下在%%b
之后的空格; 或在第二種情況下在%%a
和%%b
之后的TAB ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.