bla*_*nJa 2 linux scripting shell-script
我想逐行读取文件并将其内容放在特定位置的其他字符串中。我创建了以下脚本,但无法将文件内容放入该字符串中。
文件:cat /testing/spamword
spy
bots
virus
Run Code Online (Sandbox Code Playgroud)
脚本:
#!/bin/bash
file=/testing/spamword
cat $file | while read $line;
do
echo 'or ("$h_subject:" contains "'$line'")'
done
Run Code Online (Sandbox Code Playgroud)
输出:
or ("$h_subject:" contains "")
or ("$h_subject:" contains "")
or ("$h_subject:" contains "")
Run Code Online (Sandbox Code Playgroud)
输出应该是这样的:
or ("$h_subject:" contains "spy")
or ("$h_subject:" contains "bots")
or ("$h_subject:" contains "virus")
Run Code Online (Sandbox Code Playgroud)
第一个问题是您正在使用while read $var. 这是错误的语法,因为$var意思是“变量 var 的值”。你想要的是while read var相反。然后,变量只在双引号内展开,而不是单引号,您正在尝试以一种不必要的复杂方式处理它。您还对文件名进行了硬编码,这通常不是一个好主意。最后,作为风格问题,尽量避免UUoC。将所有这些放在一起,您可以执行以下操作:
#!/bin/bash
file="$1"
## The -r ensures the line is read literally, without
## treating backslashes specially, so without expanding
## things like `\t`.
while 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"
Run Code Online (Sandbox Code Playgroud)
请注意,通常最好使用printf而不是echo. 而且,在这种情况下,它甚至使事情变得更简单,因为您可以将echo上述内容替换为:
printf 'or ("$h_subject:" contains "%s")\n' "$line"
Run Code Online (Sandbox Code Playgroud)
将此另存为foo.sh. 使其可执行并以文件为参数运行它:
./foo.sh /testing/spamword
Run Code Online (Sandbox Code Playgroud)