繁体   English   中英

无需额外软件,即可替换文本每行中第n个出现的字符串

[英]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.

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