使用变量“grep”文件的脚本

使用变量“grep”文件的脚本
while read wholeline
do
  echo ${wholeline} --outputs John Jones
  #grab all the lines that begin with these values
  #grep '^John Jones' workfile2   --works, prints contents of workfile2 where the 1st matches
  grep '^${wholeline}' workfile2  # --does not work. why? it should be the same result.
done < workfile1

workfile1John Jones包含文件中行开头的值。

workfile2John Jones包含文件中行开头的值。

我怎样才能改变第二个grep语句以使其起作用?它什么也没捡到。

答案1

您正在使用单引号,请尝试使用双引号。对于 shell 扩展变量,需要使用双引号。

while read wholeline
do
  echo ${wholeline} --outputs John Jones
  #grab all the lines that begin with these values
  #grep '^John Jones' workfile2   # --works, prints contents of workfile2
                                  # where the 1st matches
  grep "^${wholeline}" workfile2  # --does work now, since shell 
                                  # expands ${wholeline} in double quotes
done < workfile1

相关内容