首页 > 解决方案 > 如何在目录中搜索单词并将输出写入其他文件中,该文件应该具有文件名,后跟在该文件中找到的测试用例

问题描述

for i in `cat /auto/qalogs/out.txt` ; do echo $i; grep -ril $i /auto/tools/; done > /auto/qalogs/out1.txt

我有一个文件(/auto/qalogs/out.txt),每行仅包含测试用例名称。我需要搜索给定目录中文件中存在的每个测试用例,输出应该是在该文件中找到的文件名和测试用例。

文件的输出应如下所示:格式可以是任何格式,但应在该文件中找到文件名和测试用例。

filename1:在文件中找到的测试用例列表

filename2:在文件中找到的测试用例列表

例子 :

/auto/tools/file/file1.rb:tc1、tc2、tc3
/auto/tools/file/file2.rb:tc4、tc5、tc6

得到如下输出:

tc1

/auto/tools/file/file1.rb

tc3

/auto/tools/file/file2.rb

tc2

/auto/tools/file/file1.rb

如果需要任何详细信息,请告诉我

标签: linuxshell

解决方案


根据我对您的问题的理解,这应该让您大致了解一种方法 - 它不是世界上最有效的,但它应该很容易理解并适应您的需求:

#!/bin/bash

# Make bash array of all filenames to look in and all test cases to look for
files=( $(find . -type f) )
cases=( $(cat testcases.txt) )

printf "################################################################################\n"
printf "Looking in these files:\n"
printf "%s\n"  "${files[@]}"
printf "################################################################################\n"
printf "\n"
printf "################################################################################\n"
printf "For these cases\n"
printf "%s\n" "${cases[@]}"
printf "################################################################################\n"
printf "\n"

# Look through all files in array "files"
for f in "${files[@]}" ; do
   # Clear out the results for this file, so we know if we found any cases
   res=""
   # Check if this file contains each case
   for c in "${cases[@]}" ; do
      if grep -q -m1 -w "$c" "$f" ; then
         # If it does, append this case to our result string "res"
         res="$res $c"
      fi
   done
   # If we found any test cases, print the filenames and the cases we found
   if [ ! -z "$res" ]  ; then
      echo "$f: $res"
   fi
done

推荐阅读