I want to read file line by line and put its content to other string in specific place. I have created the below script but unable to put file content in that string.

File: cat /testing/spamword





cat $file | while read $line;


echo 'or ("$h_subject:" contains "'$line'")'



or ("$h_subject:" contains "")

or ("$h_subject:" contains "")

or ("$h_subject:" contains "")

The output should be like:

or ("$h_subject:" contains "spy")
or ("$h_subject:" contains "bots")
or ("$h_subject:" contains "virus")
  • 1
    You're using the wrong tools... Try sed 's/.*/or ("$h_subject:" contains "&")/' file Nov 26, 2016 at 12:00

2 Answers 2


The first problem is that you're using while read $var. That's wrong syntax since $var means "the value of the variable var". What you want is while read var instead. Then, variables are only expanded inside double quotes, not single ones, and you're trying to deal with that but in a needlessly complex way. You're also hard-coding the file name which is usually not a good idea. Finally, as a matter of style, try to avoid UUoC. Putting all this together, you can do:


## 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
    ## 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"

Note that it's generally better to use printf instead of echo. And, in this case, it even makes things simpler since you can replace the echo above with:

printf 'or ("$h_subject:" contains "%s")\n' "$line" 

Save this as foo.sh. make it executable and run it with the file as an argument:

./foo.sh /testing/spamword

use like this

echo "or (\$h_subject: contains $line)"

you should not use $line in while.. better you can use the below code.


while read line;
echo "or (\"\$h_subject:\" contains \"$line\")"
done < ${file}
  • but needs bots, spy and virus in commas "bots" "spy" "virus". As i have mentioned above.
    – blaCkninJa
    Nov 26, 2016 at 10:40
  • Check my recent answer
    – Kamaraj
    Nov 26, 2016 at 10:44
  • according to your recent answer output is or ($h_subject: contains bots) but it should be or ("$h_subject:" contains "bots")
    – blaCkninJa
    Nov 26, 2016 at 10:51
  • Answer modified... Please check now
    – Kamaraj
    Nov 26, 2016 at 10:53
  • Yup its working now, thanks for your help :)
    – blaCkninJa
    Nov 26, 2016 at 11:23

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .