[英]formatting issue in printf script
I have a file stv.txt containing some names 我有一个包含一些名称的文件stv.txt
For example stv.txt is as follows: 例如stv.txt如下:
hello
world
I want to generate another file by using these names and adding some extra text to them.I have written a script as follows 我想通过使用这些名称并向其中添加一些额外的文本来生成另一个文件。我编写了如下脚本
for i in `cat stvv.txt`;
do printf 'if(!strcmp("$i",optarg))' > my_file;
done
if(!strcmp("$i",optarg))
if(!strcmp("hello",optarg))
if(!strcmp("world",optarg))
how can I get the correct result? 如何获得正确的结果?
This is a working solution. 这是一个可行的解决方案。
1 All symbols inside single quotes is considered a string.
1单引号内的所有符号均视为字符串。
2 When using printf, do not surround the variable with quotes.2使用printf时,请勿在变量两端加上引号。 (in this example)
(在此示例中)
The code below should fix it,以下代码可以解决该问题,
for i in `cat stvv.txt`;
printf 'if(!strcmp('$i',optarg))' > my_file;
done
basically, break the printf statement into three parts. 基本上,将printf语句分为三个部分。
1: the string 'if(!strcmp('
1:字符串'if(!strcmp('
2: $i (no quotes)2:$ i(无引号)
3: the string ',optarg))'3:字符串',optarg))'
hope that helps! 希望有帮助!
To insert a string into a printf
format, use %s
in the format string: 要将字符串插入
printf
格式,请在格式字符串中使用%s
:
$ for line in $(cat stvv.txt); do printf 'if(!strcmp("%s",optarg))\n' "$line"; done
if(!strcmp("hello",optarg))
if(!strcmp("world",optarg))
The code $(cat stvv.txt)
will perform word splitting and pathname expansion on the contents of stvv.txt
. 代码
$(cat stvv.txt)
将上的内容进行分词和路径扩展stvv.txt
。 You probably don't want that. 您可能不想要那样。 It is generally safer to use a
while read ... done <stvv.txt
loop such as this one: 通常,使用
while read ... done <stvv.txt
循环这样更安全:
$ while read -r line; do printf 'if(!strcmp("%s",optarg))\n' "$line"; done <stvv.txt
if(!strcmp("hello",optarg))
if(!strcmp("world",optarg))
cat
cat
If you are using bash
, then $(cat stvv.txt)
could be replaced with the more efficient $(<stvv.txt)
. 如果使用的是
bash
,则可以用效率更高的$(<stvv.txt)
代替$(cat stvv.txt)
$(<stvv.txt)
。 This question, however, is tagged shell
not bash
. 但是,这个问题被标记为
shell
而不是bash
。 The cat
form is POSIX and therefore portable to all POSIX shells while the bash form is not. cat
形式是POSIX,因此可移植到所有POSIX shell,而bash形式则不是。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.