[英]Delete a line in txt file after a specific keyword
我有一個txt文件,例如:
sample text1
sample text2
sample text3
我需要它是:
sample
sample
sample
基本上,我需要刪除給定短語之后的整行,在這種情況下,就是“ sample
”關鍵字
有人能幫我嗎? 我更喜歡vbscript或獨立的東西,我可以為此做一個批處理
問候,
(獲取內容sample.txt)-替換'。* sample(。+)','$ 1'| 輸出文件sample.txt
這將在.cmd或.bat文件中起作用:
for /f "tokens=1" %%i in ('type file1') do @echo %i >> file2
由於您使用Powershell標記了問題,因此我將為您提供Powershell解決方案:
$target='sample'
foreach ($line in gc .\foo.txt){$line.substring(0,$target.length)|out-file -append bar.txt}
我假設每一行都以“樣本”開頭。
如果“示例”文本在行中的任何位置,這應該起作用:
$target='sample'
foreach ($line in gc .\foo.txt){$line.substring(0,$line.indexof($target)+$target.length)|out-file -append bar.txt}
使用Just Vbscript,您可以實現以下目標
Option Explicit
Dim oFSO, oTxtFile, sLine ,filePath, cTxtFile
Const ForReading=1
Const ForWriting=2
filePath ="C:\Documents and Settings\Amol\Desktop\Converted\test.txt"
'' Filepath is your local path to txt file
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oTxtFile = oFSO.OpenTextFile(filePath, 1)
Set cTxtFile = oFSO.CreateTextFile(filePath & ".tmp")
Do Until oTxtFile.AtEndOfStream
sLine = oTxtFile.ReadLine
If InStr(sLine,"sample") <> 0 Then
sLine = Left(sLine, InStr(sLine,"sample") -1 )&"sample"
cTxtFile.WriteLine(sLine)
End if
Loop
oTxtFile.Close
cTxtFile.Close
oFSO.DeleteFile(filePath)
oFSO.MoveFile filePath&".tmp", filePath
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.