Jump to content

Find and replace a string in a text file


gaviel

Recommended Posts

I wanted to replace a strings in a large text file .. what would be the fastest way ?!

 

e.g the text file contains ..

 

INSERT INTO `subjects` VALUES (1, 'some text here', 'some text here', 'some text here');

INSERT INTO `subjects` VALUES (2, 'some text here', 'some text here', 'some text here');

INSERT INTO `subjects` VALUES (3, 'some text here', 'some text here', 'some text here');

INSERT INTO `subjects` VALUES (4, 'some text here', 'some text here', 'some text here');

INSERT INTO `subjects` VALUES (5, 'some text here', 'some text here', 'some text here');

 

I wanted to replace the string " VALUES (1, " with  "VALUES (" in each line ..

I'm new in PHP so any response would be much appreciated .. thanks

My regular expression experience leaves something to be desired, but I think something like this might work (or set you on the path towards something that works)...

 

$in_file = file('original.txt');
$out_file = 'replace.txt';

$pattern = '/VALUES \(.*[0-9],\s/';
$replace = "VALUES (";
$newTxt = array();

foreach($in_file as $line) {
        $newTxt[] = preg_replace($pattern, $replace, $line);
}

file_put_contents($out_file, $newTxt);

My regular expression experience leaves something to be desired, but I think something like this might work (or set you on the path towards something that works)...

 

$in_file = file('original.txt');
$out_file = 'replace.txt';

$pattern = '/VALUES \(.*[0-9],\s/';
$replace = "VALUES (";
$newTxt = array();

foreach($in_file as $line) {
        $newTxt[] = preg_replace($pattern, $replace, $line);
}

file_put_contents($out_file, $newTxt);

 

thanks for the response .. Tried it and work real nice fast ..

but the problem is, not only the string "VALUES ({$int_here}, " got replace ..

 

with some fields that has an instance of 5, 4, 3, 2, 1 got replace too ..

 

E.G ..

 

INSERT INTO `subjects` VALUES (5, 'some text here', 'some text here with 5, 4, 3, 2, 1', 'some text here');

 

any solutions?

If this is just a one-time thing, you could add a column to the table (at the beginning), do the batch INSERTs as-is, then drop the column...

 

what will happen to the ID then which is the primary key ?! wouldn't it affect the ID's?

 

and addition to my post above to be more clearer ..

 

E.G ..

 

INSERT INTO `subjects` VALUES (5, 'some text here', 'CWSLAI 11, another text here', 'some text here');

 

Then the ouput would be :

 

INSERT INTO `subjects` VALUES (another text here', 'some text here');

 

which cut out

VALUES (5, 'some text here', 'CWSLAI 11,

and got replace with

INSERT INTO `subjects` VALUES (

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.