Link to home
Start Free TrialLog in
Avatar of sanjay_thakur
sanjay_thakur

asked on

Delete a line in a text file using c program/perl script + system call

Hi,
I need to execute a perl script from a c program. so I presume I have to use System call. I need to pass 2 arguments to the perl script.
Arg1: filename
Arg2: string

The script should search & delete  the line with the matching string.
It should return appropriate retVal back to the System code so that
the c program can check against it.

A functioning code snippet will be helpful since I am not much
fimiliar with perl.

Also is there any way to do this in C without creating a new file.

Thanks in advance for help and feedback.
Avatar of FishMonger
FishMonger
Flag of United States of America image

I didn't test this so it may need a minor tweek.

#!/usr/bin/perl -w

$file = $ARGV[0];
$string = $ARGV[1];

open F, $file or die $!;
unlink $file if ( grep(/\Q$string/, <F>) );
int ret;
char *cmd = (char *)malloc(strlen(filename)+strlen(string)+40);
sprintf(cmd,"perl -i -pe '$ret+=s/.*\\Q%s\\E.*//s;END{exit $ret}' %s",string,filename);
ret = system(cmd);
printf("%d lines deleted\n",ret>>8);
Oops, I was deleting the file not the string in the file.  Go with ozo's solution.
Avatar of sanjay_thakur
sanjay_thakur

ASKER

HI ozo,
I am getting this error

perl cmd = perl -i -pe'$ret+=s/.*\Q/etc/vmkiscsi.conf\E.*//s;END{exit $ret}'DiscoveryAddress=10.17.235.127:3260
Bareword found where operator expected at -e line 1, near "s/.*\Q/etc/vmkiscsi"
Backslash found where operator expected at -e line 1, near "conf\"
syntax error at -e line 1, near "s/.*\Q/etc/vmkiscsi"
Substitution pattern not terminated at -e line 1.


sprintf(cmd,"perl -i -pe '$ret+=s#.*\\Q%s\\E.*##s;END{exit $ret}' %s", string, filename);
where # is a character not contained in string
I replaced # with Z since this is not in the string

This is what I get


perl cmd = perl -i -pe'$ret+=sZ.*\Q/etc/vmkiscsi.conf\E.*ZZs;END{exit $ret}'DiscoveryAddress=10.17.235.127:3260
Bareword found where operator expected at -e line 1, near "*\Q"
        (Missing operator before Q?)
Backslash found where operator expected at -e line 1, near "conf\"
syntax error at -e line 1, near "*\Q"
syntax error at -e line 1, near "10.17.235.127:"
Execution of -e aborted due to compilation errors.


Was I not supposed to replace all the #?


ASKER CERTIFIED SOLUTION
Avatar of ozo
ozo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thank you for your prompt help and patience and the solution.