如何使用正则表达式或类似方法替换所有行以添加文本?

时间:2014-06-22 16:32:31

标签: regex notepad++ str-replace

我有一个文本文件:

"C:\User\EDITED_FirstFile.txt"
"C:\User\EDITED_Randomfile2.txt"
"C:\User\EDITED_Anotherfile1.txt"

我想更改这些文件,以便它们在最后更新:

"C:\User\EDITED_FirstFile.txt abhsbahsbhabhabsha C:\User\EDITED_TMPFirstFile.txt"
"C:\User\EDITED_Randomfile2.txt abhsbahsbhabhabsha C:\User\EDITED_TMPRandomfile2.txt"
"C:\User\EDITED_Anotherfile1.txt abhsbahsbhabhabsha C:\User\EDITED_TMPAnotherfile1.txt"

这样它会自动将第一个文件输入到C:\ User \ EDITED_TMP * .txt中,如上所述。我怎么能这样做(正则表达式?)?

修改

感谢您的回复。这个实际的文件非常冗长(侧面,不是直线),上面只是一部分所以看起来更像是

"C:\User\EDITED_FirstFile.txt abhsbahsbhabhabsha C:\User\EDITED_TMPFirstFile.txt ...some random text.... C:\User\123_FirstFile.txt randomtext " etc. etc.
"C:\User\EDITED_Randomfile2.txt abhsbahsbhabhabsha C:\User\EDITED_TMPRandomfile2.txt ...some random text.... C:\User\123_Randomfile2.txt randomtext " etc. etc.
"C:\User\EDITED_Anotherfile1.txt abhsbahsbhabhabsha C:\User\EDITED_TMPAnotherfile1.txt ...some random text.... C:\User\123_Anotherfile1.txt randomtext " etc. etc.

3 个答案:

答案 0 :(得分:1)

你的正则表达式是,

^"([^_]*\_)([^"]*)

DEMO

您的PHP代码将是,

<?php
$string = <<<EOT
"C:\User\EDITED_FirstFile.txt"
"C:\User\EDITED_Randomfile2.txt"
"C:\User\EDITED_Anotherfile1.txt"
EOT;
$pattern = '/(?m)^"([^_]*\_)([^"]*)/i';
$replacement = "\"$1$2 abhsbahsbhabhabsha $1TMP$2";
echo preg_replace($pattern, $replacement, $string);
?>

输出:

"C:\User\EDITED_FirstFile.txt abhsbahsbhabhabsha C:\User\EDITED_TMPFirstFile.txt"
"C:\User\EDITED_Randomfile2.txt abhsbahsbhabhabsha C:\User\EDITED_TMPRandomfile2.txt"
"C:\User\EDITED_Anotherfile1.txt abhsbahsbhabhabsha C:\User\EDITED_TMPAnotherfile1.txt"

答案 1 :(得分:0)

以下是使用PHP执行此操作的最简单方法:

$lines = file('test.txt'); //Read test.txt
foreach($lines as $line) { //Loop through all the lines
    $line = trim($line, "\n"); //Remove newline characters
    $final = $line . ' abhsbahsbhabhabsha ' . str_replace('EDITED_', 'EDITED_TMP', $line . "\n"; //Replace what's needed and add a new line
    file_put_contents('test2.txt', $final, FILE_APPEND); //Do whatever
}

答案 2 :(得分:0)

Notepad++

找到:^"(.*)"$
替换为:"$1 abhsbahsbhabhabsha $1"

使用正则表达式模式的分组功能,将其括在括号()中并使用$1获取匹配的组。

快照:

enter image description here