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")
  • 1
    You're using the wrong tools... Try sed 's/.*/or ("$h_subject:" contains "&")/' file – don_crissti Nov 26 '16 at 12:00
5

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

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
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}
  • but needs bots, spy and virus in commas "bots" "spy" "virus". As i have mentioned above. – blaCkninJa Nov 26 '16 at 10:40
  • Check my recent answer – Kamaraj Nov 26 '16 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 '16 at 10:51
  • Answer modified... Please check now – Kamaraj Nov 26 '16 at 10:53
  • Yup its working now, thanks for your help :) – blaCkninJa Nov 26 '16 at 11:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.