2

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

spy
bots
virus

Script:

#!/bin/bash

file=/testing/spamword

cat $file | while read $line;

do

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

done

Output:

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

2 Answers2

6

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:

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

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
terdon
  • 242,166
3

use like this

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

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

#!/bin/bash

file=/testing/spamword
while read line;
do
echo "or (\"\$h_subject:\" contains \"$line\")"
done < ${file}
Kamaraj
  • 4,365