在特定关键字后删除txt文件中的一行

时间:2012-02-17 07:51:05

标签: powershell vbscript

我有一个txt文件,如:

sample text1  
sample text2  
sample text3  

我需要它:

sample  
sample  
sample  

基本上,我需要删除给定词组后面的整行,在这种情况下是“sample”关键字

有人能帮助我吗?我更喜欢vbscript或stanalone的东西,我可以为这个

制作一批

此致

4 个答案:

答案 0 :(得分:2)

(Get-Content sample.txt)-replace'。* sample(。+)','$ 1'| Out-File sample.txt

答案 1 :(得分:0)

这将在.cmd或.bat文件中起作用:

for /f "tokens=1" %%i in ('type file1') do @echo %i >> file2

答案 2 :(得分:0)

由于您使用PowerShell标记了您的问题,我将在powershell中为您提供解决方案:

$target='sample'
foreach ($line in gc .\foo.txt){$line.substring(0,$target.length)|out-file -append bar.txt}

我假设每一行都以“sample”开头。

如果“示例”文本在该行的任何位置,则应该起作用:

$target='sample'
foreach ($line in gc .\foo.txt){$line.substring(0,$line.indexof($target)+$target.length)|out-file -append bar.txt}

答案 3 :(得分:0)

使用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
相关问题