2014-12-19 51 views
-1

因此,我有一個巨大的列表,每行都有一些連續字符。我想刪除所有不需要的行,從234467開始。我想使用批處理文件來做到這一點,但如果使用php更簡單,它不會介意我。從以「abc」或「fgh」開頭的文本文件中刪除不需要的行

072345678 
072567863 
234567832 
467890432 
072345678 

我想用一個批處理文件刪除與234467所以編輯的文本文件開始將保持這樣的

072345678 
072567863 
072345678 
+1

請分享你的嘗試。 –

+0

我已經嘗試過使用這個功能,但沒有正常工作ren myFile.txt myFile.txt.old findstr/v/b/c:「blabla」myFile.txt.old> myFile.txt – Korpik

回答

0

使用FINDSTR的所有行。它允許正則表達式(與/R)。克拉(^)匹配行的開頭。 /V過濾掉匹配的行(而不是過濾掉不匹配的行)。

type yourfile.txt | findstr /R /V "^234" | findstr /R /V "^467" 
0

在PHP中,你可以使用這樣的事情

$text="072345678 
072567863 
234567832 
467890432 
072345678"; 
echo preg_replace('#^(234|467)([0-9]+)$#ims', '', $text); 

的file_get_contents有數據,然後爆炸,對pregreplace和的foreach如果不加空行,但使用的shell命令更快

0

這會爲最有可能的工作,你

$data = file("./foo.txt"); 
$matches = array('234', '467'); 
$out = array(); 

foreach($data AS $line) 
{ 
    // if not matches 234 OR 467, add to out array 
    $pattern = '/^(' . implode('|', $matches) . ')/'; // $pattern = /^(234|467)/ 
    if(! preg_match($pattern, $string)) 
    { 
     $out[] = $line; 
    } 
} 

// open and lock foofile 
$fp = fopen("./foo.txt", "w+"); 
flock($fp, LOCK_EX); 

// rewrite foo with valid content line by line 
foreach($out AS $line) 
{ 
    fwrite($fp, $line); 
} 
flock($fp, LOCK_UN); 
fclose($fp); 

如果您正在尋找這樣做是爲了許多文件,你可以隨時也變成一個功能

function replaceFileData(array $filesList, array $matches) 
{ 
    foreach ($filesList AS $file) 
    { 
     if (file_exists($file) && ! empty($matches)) 
     { 
      $data = file($file) 
      $out = array(); 

      foreach($data AS $line) 
      { 
       // if not matches 234 OR 467, add to out array 
       $pattern = '/^(' . implode('|', $matches) . ')/'; // $pattern = /^(234|467)/ 
       if(! preg_match($pattern, $string)) 
       { 
        $out[] = $line; 

        $fp = fopen($file, "w+"); 
        flock($fp, LOCK_EX); 
        foreach($out AS $line) 
        { 
         fwrite($fp, $line); 
        } 
        flock($fp, LOCK_UN); 
        fclose($fp); 
       } 
      } 
     } 
    } 
} 


replaceFileData(array('foo.txt', 'bar.txt'), array(234, 567)); 
0
C:\ type test.txt 
072345678 
072567863 
234567832 
467890432 
072345678 

C:\ findstr /B /V "234 467" test.txt 
072345678 
072567863 
072345678 
0

在批處理,你可以做一些事情像這樣:

@echo off 
setlocal enableDelayedExpansion 

for /f "tokens=*" %%i in (input.txt) do (
    set line=%%i 
    set line=!line:~0,3! 
    if !line! NEQ 234 (
     if !line! NEQ 467 (
      echo %%i >>out.txt 
     ) 
    ) 
) 
相關問題