Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在C中为shell脚本使用变量_C_Bash_Shell_Sed - Fatal编程技术网

在C中为shell脚本使用变量

在C中为shell脚本使用变量,c,bash,shell,sed,C,Bash,Shell,Sed,我有一个C语言的shell脚本,它被定义为 #define SHELLSCRIPT "\ sed 's/./& \ inserted text \ /20' fileA.txt > fileB.txt \ " 当这个shell脚本在终端上运行时,它会在fileB.txt中的偏移量20处插入文本inserted text。现在,我想从变量中获取这个20fileA.txt和fileB.txt #define SHELLSCRIPT "\ sed 's/./& \

我有一个C语言的shell脚本,它被定义为

#define SHELLSCRIPT "\
sed 's/./& \
inserted text \
  /20' fileA.txt > fileB.txt \
"
当这个shell脚本在终端上运行时,它会在fileB.txt中的偏移量20处插入文本
inserted text
。现在,我想从变量中获取这个
20
fileA.txt
fileB.txt

#define SHELLSCRIPT "\
    sed 's/./& \
    inserted text \
      /%d' fileA.txt > fileB.txt \
    "

char command[500];
sprintf(command, SHELLSCRIPT, 20);
system(command);
我该怎么做?我尝试了以下方法

#define SHELLSCRIPT "\
    sed 's/./& \
    inserted text \
      /$i' fileA.txt > fileB.txt \
    "
在C中,在运行上面的shell脚本之前,我运行
system(“I=20”)但是我在下面得到了这个错误

sed:1:“s/&此注释有…”:替换命令中的错误标志:“$”

如何实现这一点?

当运行
system()
时,每次都会启动一个新的shell。因此运行
i=20
的shell与运行
sed
命令的shell不同

%d
放在脚本文本中,而不是脚本文本中的
$i
。然后您可以将其用作sprintf的格式字符串,sprintf可以将命令格式化为单独的变量

#define SHELLSCRIPT "\
    sed 's/./& \
    inserted text \
      /%d' fileA.txt > fileB.txt \
    "

char command[500];
sprintf(command, SHELLSCRIPT, 20);
system(command);
运行
system()
时,每次都会启动一个新的shell。因此运行
i=20
的shell与运行
sed
命令的shell不同

%d
放在脚本文本中,而不是脚本文本中的
$i
。然后您可以将其用作sprintf的格式字符串,sprintf可以将命令格式化为单独的变量

#define SHELLSCRIPT "\
    sed 's/./& \
    inserted text \
      /%d' fileA.txt > fileB.txt \
    "

char command[500];
sprintf(command, SHELLSCRIPT, 20);
system(command);

替换脚本命令怎么样

#define SHELLSCRIPT "\
    sed 's/./& \
    inserted text \
      /%d' %s > %s \
    "
然后在执行命令之前,用变量替换:

char cmd[100 +1];
sprintf(cmd, SHELLSCRIPT , 20, "file1", "file2");
system(cmd)

替换脚本命令怎么样

#define SHELLSCRIPT "\
    sed 's/./& \
    inserted text \
      /%d' %s > %s \
    "
然后在执行命令之前,用变量替换:

char cmd[100 +1];
sprintf(cmd, SHELLSCRIPT , 20, "file1", "file2");
system(cmd)

你比我快了30秒:)@prabodhprakash这是格式化字符串的结果所在。然后您可以将其传递给
系统
。它基本上运行正常,但会生成这一额外的行作为输出。这能防止吗?你比我快30秒:)@prabodhprakash这是格式化字符串的结果所在。然后您可以将其传递给
系统
。它基本上运行正常,但会生成这一额外的行作为输出。这可以预防吗?谢谢你的帮助。如果这是我的第一个答案,我会把它标记为正确的。向上投票表示支持。谢谢你的帮助。如果这是我的第一个答案,我会把它标记为正确的。向上投票表示支持。不清楚。如果你想有变量字段,你必须在你的代码中组成字符串。您是如何获得sed
sed
的想法,或者shell通常可以访问程序的内部状态的?不清楚。如果你想有变量字段,你必须在你的代码中组成字符串。您是如何获得sed
sed
的想法,或者shell通常可以访问程序的内部状态的?