2013-08-16 2 views
1

텍스트 파일에 들어가 특정 문자를 찾은 다음 문자가있는 전체 줄을 바꾸려면 어떻게해야합니까?문자를 찾고 텍스트 파일의 전체 줄을 바꾸는 방법

다음은 텍스트 파일의 예 :

line1 
    example line2 
    others 
    ...... 
    .... 
    id: "RandomStr" 
    more lines 
    ... 

내가 "id"있는 라인을 찾아 교체해야합니다. 편집 된 텍스트 파일은 다음과 같아야합니다

line1 
    example line2 
    others 
    ...... 
    .... 
    "The correct line" 
    more lines 
    ... 

답변

2

먼저이 같은 텍스트 파일의 각 라인을 읽을 필요가 :

For Each line As String In System.IO.File.ReadAllLines("PathToYourTextFile.txt") 

Next 

다음, 당신은 당신이 일치 할 문자열을 검색 할 필요가 ; 발견하는 경우, 다음과 같이 대체 값으로 대체 :

Dim outputLines As New List(Of String)() 
Dim stringToMatch As String = "ValueToMatch" 
Dim replacementString As String = "ReplacementValue" 

For Each line As String In System.IO.File.ReadAllLines("PathToYourTextFile.txt") 
    Dim matchFound As Boolean 
    matchFound = line.Contains(stringToMatch) 

    If matchFound Then 
     ' Replace line with string 
     outputLines.Add(replacementString) 
    Else 
     outputLines.Add(line) 
    End If 
Next 

마지막으로,이 같은 파일에 데이터를 다시 쓰기 :

System.IO.File.WriteAllLines("PathToYourOutputFile.txt", outputLines.ToArray(), Encoding.UTF8) 
+0

outputLines.Add (replacementString)로 바꿔서 완벽하게 작동하도록 outputLines.Add (Replace (line, replacementString)) 행을 제외하고 모두 정상적으로 작동했습니다. 감사! – ThatGuyJay

+1

@ThatGuyJay - 예, 입력이 너무 빠르며 너무 빠릅니다. 그것을 잡아 주셔서 감사합니다, 답변을 업데이 트되었습니다. –

1

첫 경기 정규 표현식에 대한 라인. 그런 다음 일치하는 경우 새 행을 출력하십시오. 내가 VB.net 모르겠지만, C#의 기능은 무엇인가 등이 될 것입니다 :

void replaceLines(string inputFilePath, string outputFilePath, string pattern, string replacement) 
{ 
    Regex regex = new Regex(pattern); 

    using (StreamReader reader = new StreamReader(inputFilePath)) 
    using (StreamWriter writer = new StreamWriter(outputFilePath)) 
    { 
     string line; 
     while ((line = reader.ReadLine()) != null) 
     { 
      if (regex.IsMatch(line)) 
      { 
       writer.Write(replacement); 
      } 
      else 
      { 
       writer.Write(line); 
      } 
     } 
    } 
} 

그런 다음 당신이 원하는 부를 것이다 :이 도움이

replaceLines(@"C:\temp\input.txt", @"c:\temp\output.txt", "id", "The correct line"); 

희망.

관련 문제