2013-02-03 25 views
1

我試圖在日誌文件中刪除一些特殊行,所以我在嵌入式linux系統上使用了busybox的sed。sed命令在shell終端下工作正常,但在C代碼下調用'system()'時失敗

# 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. 下殼執行以下命令,一切工作正常:

    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()'調用有什麼問題?我完全是文本處理中的新手,所以任何人都可以給我一些線索?謝謝。

最好的問候, dejunl

+0

你需要使用'strcat'還是'+'而不是$ MODULE? – PeppyHeppy

+0

我想在sed命令中使用env變量,使用'strcat'可以解決這個問題嗎? – dejunl

+1

你爲什麼要將你的sed命令包裝在C程序中? –

回答

1

直客我可以看到\之前,[是要由「C」

所以你需要再增加一倍,

被吞噬系統(「sed \」/ $ MODULE \\ [/ d \「logfile」);

但外殼可能要吞下剩下的燕子是一個如此反覆翻一番

系統的一個(「sed的\」/$ MODULE \\\\ [/ d \「日誌文件」);

當然系統(「sed \」/ $ MODULE \\ [/ d \「logfile」);不能確定我在讀你提出的問題。試着用echo而不是sed來調整它,直到字符串出來,因爲你想sed看到它。

+0

哦,上帝,我的系統崩潰了,我現在無法啓動它,我會稍後嘗試你的方式。感謝您的回覆。 @Jasen – dejunl

+0

'system(「sed \」/ $ MODULE \\\\ [/ d \「logfile」);'好的,謝謝。 – dejunl

相關問題