【问题标题】:sed command works fine under shell terminal, but fails in 'system()' call under C codesed 命令在 shell 终端下工作正常,但在 C 代码下的 'system()' 调用中失败
【发布时间】:2013-02-03 09:18:33
【问题描述】:

我正在尝试删除日志文件中的一些特殊行,因此我在嵌入式 linux 系统上使用了 busybox 的 sed。

# sed
BusyBox v1.18.4 (2013-01-16 16:00:18 CST) multi-call binary.

Usage: sed [-efinr] SED_CMD [FILE]...

Options:
        -e CMD  Add CMD to sed commands to be executed
        -f FILE Add FILE contents to sed commands to be executed
        -i      Edit files in-place (else sends result to stdout)
        -n      Suppress automatic printing of pattern space
        -r      Use extended regex syntax

If no -e or -f, the first non-option argument is the sed command string.
Remaining arguments are input files (stdin if none).
  1. 在shell下执行以下命令,一切正常:

    export MODULE=sshd
    sed "/$MODULE\[/d" logfile
    
  2. 但如果我尝试使用以下 C 代码来完成此操作:

    char logfile[] = "logfile";
    char module_str[] = "sshd";
    char env_str[64] = {0};
    int offset = 0;
    
    strcpy(env_str, "MODULE=");
    offset += strlen("MODULE=");
    strcpy(env_str + offset, module_str);
    putenv(env_str);
    system("sed \"/$MODULE\[/d\" logfile");
    

执行 a.out 时,我收到错误消息:

sed: unmatched '/'

我的“system()”调用有什么问题?我完全是文本处理的新手,所以任何人都可以给我一些线索吗?谢谢。

最好的问候, 退步

【问题讨论】:

  • 是否需要使用strcat+ 而不是包含$MODULE?
  • 我想在sed命令中使用一个env变量,使用'strcat'可以解决这个问题吗?
  • 为什么要将 sed 命令包装在 C 程序中?
  • 小心putenv();它使用您在环境中提供的(本地)变量,这往往会导致麻烦。确保变量具有足够长的生命周期 (static char env_str[64] = "";) 或改用 setenv() (setenv("MODULE", module_str, 1);)。
  • 1.对于 Ed Morton,上面的代码只是我用 C 编写的整个应用程序的一个 sn-p,我正在实现一个处理嵌入式系统上的日志文件的模块。 PS,谢谢你漂亮的格式。

标签: c sed


【解决方案1】:

我可以直接看到 [ 之前的 \ 将被 'C' 吞噬

所以你需要加倍,

system("sed\"/$MODULE\\[/d\"日志文件");

但是贝壳可能想吞掉剩下的那个,所以再把它加倍

system("sed \"/$MODULE\\\\[/d\"日志文件");

当然 system("sed \"/$MODULE\\[/d\" logfile");不能确定我正在阅读你提出的问题。尝试使用 echo 而不是 sed 并对其进行调整,直到字符串出现您希望 sed 看到它为止。

【讨论】:

  • 天哪,我的系统崩溃了,我现在无法启动它,我稍后会尝试你的方法。感谢您的回复。 @贾森
  • 我在 R 中遇到了同样的问题(命令在终端中有效,但在 system() 调用时无效),这为我解决了!!!谢谢!
猜你喜欢
  • 2017-03-01
  • 1970-01-01
  • 2021-01-06
  • 1970-01-01
  • 2014-04-17
  • 2013-12-28
  • 1970-01-01
  • 2020-10-17
  • 1970-01-01
相关资源
最近更新 更多