使用Unix shell脚本在另一个文本文件中搜索文本文件的每一行

时间:2015-10-17 10:50:47

标签: file unix comparison

我想使用Unix shell脚本在另一个文本文件中搜索文本文件的每一行。考虑这两个文本文件:

文件1:

    <button value="next song" onclick="nextsong()"></button>
     <iframe id="player" src=""></iframe>
    <script>
  function nextsong()
     {
  document.getElementById("player").src= "your song link";}
     </script>

file2的:

HELEN  
JOE  
FRED  
HARRY  
TERRY  

所需的输出应如下所示:

hello FRED  
bert  
JOE  
hi there  
HARRY  
JOHN  
PETE was here  
hello STEVE   

我使用的脚本如下:

HELEN not found in file2  
JOE found in file2  
FRED found in file2  
HARRY found in file2  
TERRY not found in file2  

这是我得到的输出,这是不正确的

while read name  
do  
   found="no"  
   while read line  
   do  
      echo $line | grep $name >/dev/null  
      if [ $? -eq 0 ]  
      then  
         echo $name found in file2  
         found="yes"  
         break  
      fi  
   done < file2  
   if [ $found = "no" ]  
   then  
      echo $name not found in file2  
   fi
done < file1  

这里使用的脚本或逻辑是否有问题?

1 个答案:

答案 0 :(得分:0)

这就是工作:

while read f; do
  if grep -q -o $f file2
  then
    echo $f found in file2
  else
    echo $f not fount in file2
  fi
done<file1