[英]Using variables for shell script in C
I have a shell script in C which is defined as 我在C中有一个shell脚本,其定义为
#define SHELLSCRIPT "\
sed 's/./& \
inserted text \
/20' fileA.txt > fileB.txt \
"
When this shell script is run on terminal, it inserts the text inserted text
in fileB.txt at offset 20. Now, I want this 20
fileA.txt
and fileB.txt
to be fetched from a variable. 当此shell脚本在终端上运行时,它将在fileB.txt中的偏移量20处插入文本inserted text
。现在,我希望从变量中获取这20
fileA.txt
和fileB.txt
。
How should I do that? 我该怎么办? I tried the following 我尝试了以下
#define SHELLSCRIPT "\
sed 's/./& \
inserted text \
/$i' fileA.txt > fileB.txt \
"
and in C before I run the above shell script, I run system("i=20");
在运行上面的shell脚本之前,在C中运行system("i=20");
but then I get this error below 但是然后我在下面得到这个错误
sed: 1: "s/./& this comment has ...": bad flag in substitute command: '$'
How can I achieve this? 我该如何实现?
When you run system()
, it starts up a fresh shell each time. 运行system()
,每次都会启动一个新的Shell。 So the shell that i=20
runs in is not the same shell that the sed
command runs in. 因此, i=20
运行的外壳与sed
命令运行的外壳不同。
Instead of $i
in the script text, put %d
there instead. 不在脚本文本中使用$i
,而应在其中放置%d
。 Then you can use it as a format string to sprintf which can format the command into a separate variable. 然后,您可以将其用作sprintf的格式字符串,后者可以将命令格式化为单独的变量。
#define SHELLSCRIPT "\
sed 's/./& \
inserted text \
/%d' fileA.txt > fileB.txt \
"
char command[500];
sprintf(command, SHELLSCRIPT, 20);
system(command);
how about you replace your script command 如何替换脚本命令
#define SHELLSCRIPT "\
sed 's/./& \
inserted text \
/%d' %s > %s \
"
and then you replace by your variables, before executing the command: 然后在执行命令之前,用变量替换:
char cmd[100 +1];
sprintf(cmd, SHELLSCRIPT , 20, "file1", "file2");
system(cmd)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.