简体   繁体   中英

nodejs 'exec' command doesn't execute 'sed' command properly

I have a file where I want to scan it, find the character '{' and create a new line, then add an IP on the new line and add a semi-cologne to the end of the line, then write to a config file.

I can accomplish this with the following sed command when running from shell:

sed -i 's/{/&\n1.1.1.1;/g' /tmp/test.conf

inside test.conf:

acl testACL{
};

the output from the command in shell shows:

acl testACL{
1.1.1.1;
};

works perfect! Now the problem is when I get nodejs to execute it:

        var sys = require('sys');
        var exec = require('child_process').exec;
        function puts(error, stdout, stderr) { sys.puts(stdout) };
        exec("sed -i 's/{/&\n1.1.1.1;/g' /tmp/test.conf",puts);
        return 0;

when I run the command in console: 'nodejs test.js'

I get blank output and when I check the file, the file 'test.conf' has not been altered! why?!

Also if you're thinking 'its a permissions issue!' I've had nodejs exec command write basic echos to the test config file and it worked fine.

I have also tried the 'shelljs' module with no luck there. I have tried countless combinations for hours now with no prevail! I'm puzzled.

I think you need to escape your \\n as \\\\n . Right now, it's getting parsed as a literal newline in the command, which is messing it up.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM