简体   繁体   English

Windows Batch-在txt文件中查找和编辑行

[英]Windows Batch - find & edit lines in txt file

I'm looking for a simple script that will search a text file (input.txt) with numbers listed as such: 我正在寻找一个简单的脚本,该脚本将搜索文本文件(input.txt),其中列出的数字如下:

I have basically no experience with batch coding (or any code for the matter) and am hoping someone here can assist me. 我基本上没有批处理编码(或与此有关的任何代码)的经验,希望这里有人可以帮助我。

0001
0002
0003
etc

I need the output (output.txt) to be: 我需要输出(output.txt)为:

[test]0001[/test]
[test]0002[/test] 
[test]0003[/test] 
etc 

Any help would be appreciated! 任何帮助,将不胜感激!

Edit: Someone posted a python script and then deleted it before I could test it and reply. 编辑:有人发布了python脚本,然后将其删除,然后我才能对其进行测试并回复。 I know it's not what I originally asked for but it works great! 我知道这不是我最初要求的,但是效果很好! Thank you! 谢谢!

This is it if someone finds this thread and can use it: 如果有人找到此线程并可以使用它,就是这样:

    rf = open("input.txt", 'r')
lines = rf.read().splitlines()
formatted_lines = ['[test]{}[/test]'.format(i) for i in lines]

with open('output.txt', 'w') as wf:
    for l in formatted_lines:
        wf.write("{}\n".format(l))

Here's how to transform the data from Windows Command Prompt: 以下是从Windows命令提示符转换数据的方法:

powershell -c "cat input.txt | %{\"[test]$_[/test]\"} > output.txt"

Alternatively, if you can run it straight from a PowerShell, that would be: 或者,如果您可以直接从PowerShell运行它,则可能是:

cat test.txt | %{"[test]$_[/test]"} > output.txt

That's easy and could be easily done with: 这很容易,可以通过以下方式轻松完成:

@echo off

for /F "delims=" %%A IN (input.txt) do echo [test]%%A[/test]
pause>nul & exit /b 0

This, will just echo the result in the console. 这样,将在控制台中echo显结果。 For saving it into a file, use: 要将其保存到文件中,请使用:

@echo off

for /F "delims=" %%A IN (input.txt) do (echo [test]%%A[/test])>>output.txt
pause>nul & exit /b 0

For echo ing it and save it also in a file, use: echo并将其保存在文件中,请使用:

@echo off

for /F "delims=" %%A IN (input.txt) do (
    echo [test]%%A[/test]
    (echo [test]%%A[/test])>>output.txt
)

pause>nul & exit /b 0

Note: The same about solution was proposed by LotPings in comments. 注:提出在评论LotPings 有关的解决方案是相同的。 It is adapted not to send the output of the whole for loop but of the echo command, producing the same result. 它适合于不发送整个for循环的输出,而是发送echo命令的输出,从而产生相同的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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