我想逐行读取文件并将其内容放入特定位置的其他字符串。我创建了以下脚本,但无法将文件内容放入该字符串中。
文件:cat /testing/spamword
spy
bots
virus
脚本:
#!/bin/bash
file=/testing/spamword
cat $file | while read $line;
do
echo 'or ("$h_subject:" contains "'$line'")'
done
输出:
or ("$h_subject:" contains "")
or ("$h_subject:" contains "")
or ("$h_subject:" contains "")
输出应该是这样的:
or ("$h_subject:" contains "spy")
or ("$h_subject:" contains "bots")
or ("$h_subject:" contains "virus")
答案1
第一个问题是您正在使用while read $var
.这是错误的语法,因为它的$var
意思是“变量 var 的值”。你想要的是while read var
相反的。然后,变量仅在双引号内扩展,而不是在单引号内扩展,并且您试图以一种不必要的复杂方式来处理它。您还对文件名进行硬编码,这通常不是一个好主意。最后,作为风格问题,尽量避免乌鲁克。将所有这些放在一起,您可以执行以下操作:
#!/bin/bash
file="$1"
## The -r ensures the line is read literally, without
## treating backslashes as an escape character for the field
## and line delimiters. Setting IFS to the empty string makes
## sure leading and trailing space and tabs (found in the
## default value of $IFS) are not removed.
while IFS= read -r line
do
## By putting the whole thing in double quotes, we
## ensure that variables are expanded and by escaping
## the $ in the 1st var, we avoid its expansion.
echo "or ('\$h_subject:' contains '$line')"
done < "$file"
请注意,这是一般来说更好使用printf
而不是echo
.而且,在这种情况下,它甚至使事情变得更简单,因为您可以将echo
上面的内容替换为:
printf 'or ("$h_subject:" contains "%s")\n' "$line"
将其另存为foo.sh
.使其可执行并使用文件作为参数运行它:
./foo.sh /testing/spamword
答案2
像这样使用
echo "or (\$h_subject: contains $line)"
你不应该在 while.. 中使用 $line ,你可以使用下面的代码。
#!/bin/bash
file=/testing/spamword
while read line;
do
echo "or (\"\$h_subject:\" contains \"$line\")"
done < ${file}