How to find a particular character in a file and delete it?
Each line contains a character, like this
a
b
c
f
Deleting characters from file
Moderator: General Moderators
-
shivam0101
- Forum Contributor
- Posts: 197
- Joined: Sat Jun 09, 2007 12:09 am
Linux OS and exec() available:
Code: Select all
exec("cat file.txt | grep -v 'a' | grep -v 'd' > file2.txt && mv file2.txt file.txt");There are 10 types of people in this world, those who understand binary and those who don't
-
shivam0101
- Forum Contributor
- Posts: 197
- Joined: Sat Jun 09, 2007 12:09 am
Its small, i am reading it usingIs the file small enough to read it entirely to memory, e.g. via file() or file_get_contents()?
Code: Select all
file()I am using windowsLinux OS and exec() available:
Code:
exec("cat file.txt | grep -v 'a' | grep -v 'd' > file2.txt && mv file2.txt file.txt");
-
mcog_esteban
- Forum Contributor
- Posts: 127
- Joined: Tue Dec 30, 2003 3:28 pm
Try something like:
Code: Select all
<?php
$remove[] = 'a';
$remove[] = 'd';
$contents = file_get_contents("file.txt");
$explode = explode("\n", $contents);
$final = array_diff($explode, $remove);
$handle = fopen("file.txt", "w");
fwrite($handle, implode("\n", $final));
?>I think volka's suggestion would be:shivam0101 wrote:Its small, i am reading it usingIs the file small enough to read it entirely to memory, e.g. via file() or file_get_contents()?Code: Select all
file()
Code: Select all
$new_file_contents = preg_replace('/[aefm]\n/', '', $file_contents);There are 10 types of people in this world, those who understand binary and those who don't
-
shivam0101
- Forum Contributor
- Posts: 197
- Joined: Sat Jun 09, 2007 12:09 am