ファイルを1行ずつ読み、別の文字列を挿入します。

ファイルを1行ずつ読み、別の文字列を挿入します。

ファイルを1行ずつ読み、その内容を特定の場所の他の文字列に入れたいと思います。次のスクリプトを作成しましたが、その文字列にファイルの内容を入れることはできません。

ファイル: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

最初の問題は、「変数varの値」を意味するwhile read $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

おすすめ記事